Array in Java

Learn basics of array in Java

Array is a collection of homogeneous type of data. In java array is created using "new" keyword.
Array creation involve array declaration and memory allocation.

Array can be declared in two ways.

Array Declaration :

  int [] a,b,c; // this declaration create three array 

Second way of creating array only create a single array.

Array Declaration:

  int a[],b,c;  // this declaration create one array and two variable

Array declaration in above program only create array reference variable. To allocate memory 'new' keyword is used.

Memory Allocation:

  int [] a= new int[6]; // this syntax will create array for 6 integers.

Array initialisation can be done at the time of array creation.

Array Initialisation:

  int [] a= {3,7,8,9,5,4};  // this syntax will initialise array.

Partial Initialisation:

// In partially initialised array, remaining elements initialised with default value  
  int [10] a= {3,7};  
 // a[2],a[3]...a[9] all will be having 0 

Above statement can't be written in two separate statement.

Wrong initialisation:

	  int [] a;
	  a = {3,7,8,9,5,4}; //Error 

Note ! Number of elements has to be specified at the time of memory allocation for array. Constant value has to be used to specify number of elements.

Array Creation:

	  int [] a=new int[<constant>]; 	  

Variable can't be given as number of elements in array. Because array require no. of elements at compile time but variable get their value at run time. For example program given below will show an error.

Program with error:

class array
  public static void main(String arg[])
     int a=12;
     int b[]=new int[a];  // Error

Note ! If array initialised partially then remaining elements automatically get initialised by default value.


 // file:
 class two
  public static void main(String arg[])
     int a[]=new int[10];
/* Output:

ArrayIndexOutOfBound Exception

Java won't allow programmer to access array element out of bound. For example in 'C' language if we are having an array of five element and if we try to print array value for 6th index, it will print garbage value. But in java there will be an expcetion for accessing out of bound elements.

Example :

class array1
  public static void main(String arg[])
     int a[]={12,23,34,45,2};

At execution of above program following error will be generated:

Error Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at array.main(