Java

How to initialize an Array in Java

An array in Java is a data structure that has consecutive elements of the same type. The elements are indexed, beginning from zero. In Java, an array is an object obtained from the Object class. There are three ways of creating an array: An array can be declared (created) without the length defined. In this case, the length of the array still has to be defined. An array can be created, with the length defined and automatically initialized with the default values of the array type. An array can be created with the practical values assigned to the array elements. In this case, the length of the array is indirectly defined by the number of practical values.

This article illustrates three ways of initializing an array, using the primitive type, string type, and user-defined type. The string type and the user-defined types are reference types. The article begins with the initialization of the array with a primitive type.

Initializing Array with Primitive Type

The char type will be used here. char means character. Other primitive types are done in the same way. All the code in this section takes place in the main() method. The statement,

char[] arr;

declares an array without any initial value and without the number of characters indicated. The number of characters for the array is the length of the array. Once the length has been decided upon, it remains that way until the end of the program. Another statement is needed, together with this one, to give length to this array, as follows:

char[] arr;

arr = new char[5];

Now, the array’s number of characters (length) is 5. Some initialization has taken place with the second statement. However, this is not practical initialization. It is initialization with 5 default values for char. The default value for char is the empty character, i.e. ” , it has no space.

The next code segment assigns one practical value (character) to each of the memory locations, of the 5 character variables of the array:

arr[0] = 'F';

arr[1] = 'G';

arr[2] = 'H';

arr[3] = 'I';

arr[4] = 'J';

This is an assignment or replacement. It is not initialization. Initialization was done with default values. The above two declaration statements can be done in one statement, as follows:

char[] arr = new char[5];

The name of the array is arr. char is the reserved word for char, which appears on both sides of the assignment operator. New is another operator. It creates the object with default values. The second square bracket in the whole statement has the length of the array. At this point, each element of the array still needs to be given a practical value. That is the second way of declaring an array.

The third way of declaring an array involves initialization with practical values. It is in two forms, as follows:

char[] arr = {'F', 'G', 'H', 'I', 'J'};

or

char[] arr = new char[]{'F', 'G', 'H', 'I', 'J'};

The first form has the array literal, which is called the array initializer. It is in braces. Each character is in a single quote. The array initializer indirectly determines the length of the array (number of elements). The first form does not have the new operator. The second form has the new operator. However, here, the second square brackets do not have the array’s length, as the length is implicit in the array initializer, coded next to it.

Initializing Array of Strings

The string object is a very good example of the reference type in Java. There are two kinds of types in Java: primitive and reference types. The primitive types are: boolean, byte, char, short, int, long, double, float. The following statement declares an array of strings without any length defined and any initial value (be it default or practical).

String[] arr;

Another statement is needed, together with this one, to give length to this array, as follows:

String[] arr;

arr = new String[4];

Now the number of strings (references) of the array is 4. Some initialization has taken place with the second statement. However, this is not practical initialization. It is initialization with 4 default values for String. The default value for string is null, without quotes. The following code in the main() method illustrates this:

String[] arr;

arr = new String[4];

for (int i=0; i<4; i++) {

System.out.print(arr[i]); System.out.print(' ');

}

System.out.println();

The output is:

null null null null

The following code segment assigns one practical value (string reference) to each of the memory locations, of the 4 string variables of the array:

arr[0] = "one";

arr[1] = "two";

arr[2] = "three";

arr[3] = "four";

This is an assignment or replacement. It is not initialization. Initialization was done with default values. The above two declaration statements can be done in one statement, as follows:

String[] arr = new String[4];

The name of the array is arr. A string is a reserved word for string, which appears on both sides of the assignment operator. New is another operator. It creates the object array with default values. In the whole statement, the second square bracket has the length of the array. At this point, each element of the array still needs to be given a practical value. That was the second way of declaring an array.

The third way of declaring an array involves initialization with practical values. It is in two forms, as follows:

String[] arr = {"one", "two", "three", "four"};

or

String[] arr = new String[]{"one", "two", "three", "four"};

The first form has the array literal, which is called the array initializer. It is in braces. Each character is in a single quote. The array initializer indirectly determines the length of the array (number of elements). The first form does not have the new operator. The second form has the new operator. However, here, the second square bracket does not have the length of the array, as the length is implicit in the array initializer, coded next to it.

Note: To use the string or array in Java, neither the string class nor the array class has to be imported.

User-Defined Objects

The following is an example of a user defined class:

class AClass {

int prop;

int mthd() {

return prop;

}

}

Aclass is the name of the class from which its objects will be created.

In the main() function, the following code segments can be employed:

AClass obj1 = new AClass();

obj1.prop = 1;

int ret1 = obj1.mthd();

System.out.println(ret1);

AClass obj2 = new AClass();

obj2.prop = 2;

int ret2 = obj2.mthd();

System.out.println(ret2);

AClass obj3 = new AClass();

obj3.prop = 3;

int ret3 = obj3.mthd();

System.out.println(ret3);

Each code segment creates an object of type, Aclass. Each is a user-defined object. Each code segment assigns an integer to the property (field) of each object. There are three different objects of the same class. Each code segment calls its method for its object. The output for the three code segments should be: 1 2 3, with each number in a separate line.

The declaration of an array of a user-defined class type is done in the same way as in the above cases. For example,

AClass[] arr = new AClass[3];

declares an array of three objects of type, Aclass. This statement created an array initialized with the default type value. For any reference type, including the string type, the default value is null. This means there are three values of null in the array, arr, now. The following code in main() should prove this:

AClass[] arr = new AClass[3];

for (int i=0; i<3; i++) {

System.out.print(arr[i]); System.out.print(' ');

}

System.out.println();

The output is:

null null null

The following statement initializes the array with practical objects of the Aclass type:

AClass[] arr = {obj1, obj2, obj3};

This statement is very correct. Unfortunately, the following code segment, prints out codes, instead of obj1, obj2 and obj3:

AClass[] arr = {obj1, obj2, obj3};

for (int i=0; i<3; i++) {

System.out.print(arr[i]); System.out.print(' ');

}

System.out.println();

The output is:

AClass@6ff3c5b5 AClass@3764951d AClass@4b1210ee

three different codes. The reason for this is that the array expects object literals, but object references have been given.

In the above procedure, the object names, obj1, obj2, and obj3, were created (instantiated) before writing them into the array. To work around this problem, instantiate the objects as array elements, without their names, as follows:

AClass[] arr = {new AClass(), new AClass(), new Aclass()};

From here, instead of using the object names, obj1, obj2 obj3 to access the properties and methods, use the array indexes as follows:

arr[0].prop and arr[0].mthd(); arr[1].prop and arr[1].mthd(); arr[2].prop and arr[2].mthd();

The solves the problem. And so the above three code segments can be rewritten as:

AClass[] arr = {new AClass(), new AClass(), new AClass()};

arr[0].prop = 1;

int ret1 = arr[0].mthd();

System.out.println(ret1);

arr[1].prop = 2;

int ret2 = arr[1].mthd();

System.out.println(ret2);

arr[2].prop = 3;

int ret3 = arr[2].mthd();

System.out.println(ret3);

And the ultimate output expected, is as before, that is: 1 2 3, with each number in its own line.

Conclusion

There are two kinds of types in Java: primitive types and reference types. An array can be declared without any element value and length. An array can be declared with its length but initialized to its default values by the compiler. An array can be declared, initialized with the practical values. If the values are references, and the literals cannot be used as values, then the array values should be the instantiations of the class.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.