Array Initialization in Java



ARRAY INITIALIZATION

Once we creates an array, every element by default initialized with default values. 

int[] ar = new int[2];
System.out.println(ar);         [I@(HashCode in hexa decimal format)
System.out.println(ar[0]);    0

Whenever we are trying to print any reference variable internally toString() method will be called which is implemented by default to return the string in following form. 
Classname@Hashcode_in_hexadecimal_form.

int[][] a = new int[2][3];
System.out.println(a);                 [[I@(HashCode in hexa decimal format)
System.out.println(a[0]);            [I@(HashCode in hexa decimal format)
System.out.println(a[0][0]);        0


int[][] a = new int[2][];
System.out.println(a);               [[I@(HashCode in hexa decimal format)
System.out.println(a[0]);          null
System.out.println(a[0][0]);     RE: NullPointerException


If we are trying to perform any operation on null then we will get runtime exception saying NullPointerException 

Once we creates an array, every array element by default initialized with default values, if we are not satisfied with default values then we can override these values with our customized values.

int[] x = new int[2];
x[0] = 1;
x[1] = 2;



int[] x = new int[2];
x[0] = 1;
x[1] = 2;
x[2] = 3;     RE: ArrayIndexOutOfBoundsException
x[-6] = 4;    RE: ArrayIndexOutOfBoundsException
x[2.5] = 5;  CE: Possible Loss of precision
                          found double 
                          required int 


If we are trying to access array element with out of range index (either positive or negative int value) then we will get runtime exception saying ArrayIndexOutOfBoundsException


ARRAY DECLARATION, CREATION AND INITIALIZATION IN A SINGLE

We can declare create and initialize an array in single line.
int[] x = {1,2,4};
char[] ch = {'a','e','i'};
String[] s = {"a","aa","aaa"};

We can use this shortcut for multi dimensional arrays also.
int[][] sx = {{1,2,3},{1,2,3,4,5}};

If we want to use this short cut compulsory we should perform all activities in a single line. If we are trying to divide into multiple lines then we will get compile time error.
int[] x = {1,2,3};  

int[] z ;
z = {1,2,3};  CE: Illegal start of expression

Comments

Popular posts from this blog

Variables (Part-1)

length vs length()

Arrays in Java