Skip to main content

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.

Comments

Popular posts from this blog

Architecture Complexity

Here are the items to consider: Coding to an interface Service Oriented Architecture Automated Testing Domain Driven Design Custom Data Access Layer Layered architecture Complexity is relatively equal the number of lines of code. Note that complexity is not bad. It must be justified.

Repair Windows 7 System Files

8 out of 10 average PC users have their box’s system files altered by malwares, viruses, etc. We usually reinstall the OS if the antivirus and anti malware software did not perform their job well. Here’s one way to fix the corrupted system files without the need of restarting your Windows 7 box. 1. Run the Command Prompt as Administrator 2. Type the following command C:\Windows\system32\> sfc /scannow 3. After the verification phase, you will receive a message about your system files’ integrity Windows Resource Protection did not find any integrity violations.