Java - Arrays

  • Java array is an object the contains similar data type of elements that have contiguous memory location.
  • We can store only fixed set of elements in a java array.
  • Array in java is index based, first element of the array is stored at 0 index.

							  
dataType[] arr=new datatype[size]; (or)  
dataType []arr=new datatype[size]; (or)  
dataType arr[]=new datatype[size];

Example :

							  
public class SampleEx {
	public static void main(String[] args) {
		int a[]=new int[5];//declaration and instantiation 
			a[0]=10;//initialization  
			a[1]=20;  
			a[2]=30;  
		        a[3]=40;  
			a[4]=50;
			// or int a[]={10,20,30,40,50};//declaration, instantiation and initialization 
			//printing array  
		     for(int i=0;i<a.length;i++){
		        System.out.println(a[i]);  
		     }
	}

}

Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

BytecodeTechnosolutions.com | Raju