Sunday, May 18, 2008

Nonprimitive Data Types in Java

Nonprimitive data types in Java are reference variables (object references), arrays and enums. All nonprimitive data types are references to memory where the objects live.


[objects]


References provide access to objects. The declaration syntax is just the same as with primitives.



Decryptor decryptor;

The above example shows that we are creating a reference to a Decryptor object. Take note that no real object is created yet.


The object is created through the new operator.



decryptor = new Decryptor();

The reference decryptor now points to a Decryptor object in the heap.


[arrays]


Arrays are objects used to hold a collection of primitive or nonprimitive data of the same type. Take note that even if an array holds primitive data, it is always an object.


Steps for creating an array:


1. Declaration of an array variable (reference)



char[] charArray; //or
char charArray[];

2. Instantiation of an array of a certain size



charArray = new char[8];

3. Initialization of each array element.



charArray[0] = 'k';
charArray[1] = 'a';
charArray[2] = 'r';
charArray[3] = 'e';
charArray[4] = 'n';
charArray[5] = 'e';
charArray[6] = 'v';
charArray[7] = 'e';

Once a size is given to an array, it cannot be changed later.


[enums]


The data type enum is used to store a predetermined set of values or constants. Examples are the months in a year, the days in a week, etc.


Steps for creating an enum:


1. Define the enum type with unique named values



enum ShortWeek {MON, TUE, WED, THU, FRI, SAT, SUN};

2. Assign a reference to the enum type



ShortWeek monday = ShortWeek.MON;

You can only create X instances of an enum type, where X is the number of elements that the enum type holds.

No comments: