Arrays in Java

How to initialize an array in java ?

We can initialize an array in java as shown below.

int[] numbers = new int[4]; 

//int is the type of the array
//square brackets [] is the array symbol
//in int[4], 4 is the size of the array.

Note: To initialize an array in java we need to specify the size of the array.

If we know the initial values of the array we can initialize it as shown below.

//All are valid.
int[] numbers = new int[]{1,2};
int[] numbers = {1,2};
String[] animals = {"dog","cat"};

The square bracket on the left side can be in front of the type or name. It can even have a space in-between.

//All are valid.
String animals [] = {"dog","cat"};  //with space after name.
String [] animals = {"dog","cat"};
String[] animals = {"dog","cat"}; //common
String animals[] = {"dog","cat"};
How to initialize an array in java if I don’t know the size at the time of initialization ?

If you are not sure about the size of the array at the time of initialization use collections like ArrayList. Another option is to provide a big number for the size. But keep in the mind the array will be filled up with the default type values. For example the below code will create an array of 4 zeroes.

int numbers[] = new int[4];
for (int n:numbers) {
    System.out.print(n); //Output 0000
}

Below code will create an array of 4 nulls as the default value of String is null.

String names[] = new String[4];
for (String n:names) {
    System.out.print(n);  //nullnullnullnull
}

An array will not resize automatically but an ArrayList does. If you set the initial size as 0 for an array and then try to add an element the JVM throws ArrayIndexOutofBoundsException at runtime.

String names[] = new String[0];
names[0] = "name1";  //throws java.lang.ArrayIndexOutOfBoundsException
How to add an element to an array in java ?

To add an element use the index value inside the square bracket and assign the values as shown below.

int[] numbers = new int[2];
numbers[0] = 1;
numbers[1] = 2;
for (int n:numbers) {
    System.out.print(n);  //Output 12
}
How to find the size of an array in java ?

Use arrayname.length as shown below.

int[] numbers = {1, 2, 5, 7};
System.out.println(numbers.length);  //Output 4