How to declare and initialize array in java / Everything about arrays in java

What is an Array?
An array is a group of elements of similar data type. Array elements can be either primitives(such as int, float, double) or objects(such as String, Person, Dog etc.). Array itself is an object irrespective of its element types and is stored on the heap.
If an array contains primitive elements, it should be called an array of primitives but it is incorrect to say primitive array as there is no such thing as primitive array.


Declaring Array
An array in java can hold elements of only one type. Thus, it is declared by stating the type of elements that it will contain. Type should be followed by square brackets and a user defined name of the variable that will represent the array. Following declarations of an array are possible.

// array of numbers
double [] numbers;     //recommended
double numbers[];      // allowed but not recommended
// array of objects
Dog[] dogs;

It is not permitted to provide the size of array at the time of declaration and will raise a compiler error. This is because memory is not allocated for the array till it is created.
Creating Array
Till now we only declared the array which tells JVM about the type of elements the array will contain. Creating an array means actually constructing the array where we specify the size of the array(number of elements in the array) so that JVM can allocate memory for it. An array can be created in two ways:
1. Using new operator
Create array just like an object is created. Example,

int[] numbers = new int[5];   // create array of five integers
Dog[] dogs = new Dog[5];   // create array of five dog objects
It is not possible to change the size of array after it is created. You can not increase or decrease the number of elements that an array can hold after it is created.

2. Direct initialization
Provide elements right at the time of declaration. You do not need to provide the size when using this method since it is calculated by the number of elements given while initialization. Also, elements of the array are provided within curly braces. Example,

int[] numbers = {2, 3, 45, 6, 7, 8};   // create an array of 6 elements
Dog[] dogs = {new Dog("a"), new Dog("b")}; // create array of 2 dog objects

It is also possible to split array declaration and initialization in two different statements as shown below.

int[] numbers;    // declare array
numbers = new int[5];   // create an array of 5 elements

This is usually done when the size of the array at the time of declaration is not known.
But you can not do this when directly initializing array elements. That is, following will invite a compiler error.

int[] numbers;    // declare array
numbers = {2, 3, 45, 6, 7, 8};  // NOT allowed


Array memory representation
An array is an object and objects in java are stored on heap memory. Thus an array of primitive elements(such as integer) will be stored as shown below.
representation of array of primitive elementsAn array whose elements are themselves objects is represented as below.

representation of array of objects

Default values of elements of an integer array is 0 while all elements of an object array will be initialized to null after the array is created but no elements are assigned to it.

Accessing Array elements
Array elements are index based with index starting from 0 to length of array – 1. That is, for an array of five elements, its index will range from 0 to 4 with index of first element being 0, second element 1 and last element 3.
For accessing an array element, its index is used. Syntax to access an individual array element is by using the name of array reference variable followed by its index in square brackets. Thus, for an array of 5 elements,

numbers[1]  will return the second array element
numbers[0] will return the first array element
numbers[4] will return the last array element

If you try to access array index which is outside the length of array, then a java.lang.ArrayIndexOutOfBoundsException is raised. Example, for an array of length 5, accessing indexes above 4 and below 0 will raise this exception.


Length of array
Length of array is the total number of elements in the array and can be retrieved using its length property. Remember the index of array elements will be from 0 to length – 1. Example,

String[] colors = {"Violet", "Blue", "White", "Black"};
System.out.println(colors.length);   // will print 4

Looping over an Array
Since an array is a collection of elements, it can be iterated over by a loop. This loop can be a normal loop which uses index based iteration such as for or while loop or enhanced for loop(also referred as foreach loop).
Index based looping
This approach initializes a loop from 0 till length of array – 1. In every iteration, you can access the current array element using its index. Example,

int[] numbers = {23, 45, 62, 1};  // length is 4
// loop from 0 till 3
for(int index = 0; index < numbers.length - 1; index++) {
   System.out.println("Element at position " + index + " is " + numbers[index]);
}

which prints

Element at position 0 is 23
Element at position 1 is 45
Element at position 2 is 62
Element at position 3 is 1


Loop using enhanced for
This approach does not use indexing. Instead, it uses a variable which is of the same type as the array. In every iteration, this variable contains the current array element. Example,

String[] languages = {"java", "python", "C#"};
System.out.println("Languages are: ");
for(String lang: languages) {
   System.out.println(lang);
}

Notice the use of colon(:) after variable name. Above code outputs

Languages are:
java
python
C#

Modifying Array elements
Elements of an array can be modified after its creation using assignment operator(=) and the element index. Assign a new value to the element which needs to be modified using its index as shown below.

String[] fruits = {"Apple", "Banana", "Orange", "Grapes"};
fruits[1] = "Papaya";   // replace Banana with Papaya

Assigning elements to array using a loop
It is also possible to initialize array elements after its creation using a loop and assignment operator. This can only be done using index based loop and not using enhanced for loop. Example,

int[] numbers = new int[4];  // create an array of 4 elements
// loop from 0 till 3
for(int index = 0; index < numbers.length - 1; index++) {
   // assign element to current position
   numbers[index] = index * 10;   
}

Mark Your Impression

Close Menu