Array Initialisation
When an array is created, every element is by default is initialised with default values
import java.lang.*;
class Test {
public static void main(String[] args) {
int[] a = new int[3];
System.out.println(a); // [I@379619aa
System.out.println(a[0]); // 0
}
} When printing any reference variable, internally, toString() method will be called, which is implemented by default to return the string in the following form: classname@hashcode_in_dexadecimal_form
import java.lang.*;
class Test {
public static void main(String[] args) {
int[][] a = new int[2][3];
System.out.println(a); // [[I@581619ea
System.out.println(a[0]); // [I@721639ee
System.out.println(a[0][0]); // 0
}
} In the example above, the value of System.out.println(a[0]); is a reference to another array, since this is a 2d array, and as discussed before, this is the behaviour of arrays of array style.
import java.lang.*;
class Test {
public static void main(String[] args) {
int[][] a = new int[2][];
System.out.println(a); // [[I@383619ea
System.out.println(a[0]); // null
System.out.println(a[0][0]); // Runtime Exception: Nullpointer Exception
}
} In the example above, only the base was specified, meaning the size of the array (a[0]) being referenced is unknown, hence it is null. Since it is null, the value of a[0][0] throws a NullPointerException because the array does not exist.
When trying to perform any operation on null, there will be a null pointer runtime exception.
import java.lang.*;
class Test {
public static void main(String[] args) {
int[] a = new int[6];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;
a[5] = 60;
a[6] = 70; // INVALID: RuntimeException - ArrayIndexOutOfBoundsException
a[-6] = 80; // INVALID: RuntimeException - ArrayIndexOutOfBoundsException
a[2.5] = 90; // INVALID: Compile time error - Possible loss of precision, found double, required int
}
}Once an array is created, every array element is by default initialised with default values. These default values can be overridden by custom values The code snippet above shows an array overriding default values with custom values.
When trying to access an array element without of range index (either positive or negative int value) then a RuntimeException will be thrown with the ArrayIndexOutOfBoundsException.
