Core Java Tutorial

 
 

Arrays

An array is defined as a collection of elements which are of same data types.Arrays always will have fixed size , once if you declare the size of an array it won't allow you to call values more than that size and if you try to call a value which is out of range compiler will throw "ArrayIndexOutOfBound Exception".

Keypoints about Arrays

  1. Values stored in array are called elements.
  2. Positions of elements are identified by using indexes(index start with 0).
  3. Array values are stored in continuous memory allocation.
  4. Length of an array is size of the array subtract by 1(i.e (student.length()-1) , here student is array variable.
  5. Array size should be declared at the creation time itself
  6. Arrays are unidimensional or multidimensional
  7. Every element in a array should be of same data type
Arrays Declaration

Syntax of Array

There are different ways to declare and initialize an array.Here are some of the ways to declare and intiliaze an array.

1) int[] students= new int[10];  //  Here i am declaring array with size.
2) int[] student = new int{1,2,3,4,5,6,7,8,9,10}; // Here i am declaring array with values.
3) String[] student1 ; // Here i am just declaring the array , not intiliazing any values.

Sample Programs

   EX:1
   
  public class Arrays {
  public static void main(String[] args) {
  int arr[][] = new int[5][0];
        arr[0] = new int[1];
        arr[1] = new int[2];
        arr[2] = new int[3];
        arr[3] = new int[4];
        arr[4] = new int[5];
  
        int i, j, k = 0;
        for (i = 0; i < 5; i++) {
            for (j = 0; j < i + 1; j++) {
                arr[i][j] = k;
                k++;
            }
        }
        for (i = 0; i < 5; i++) {
            for (j = 0; j < i + 1; j++) {
                System.out.print(" Values: " + arr[i][j]);
                k++;
            }
            System.out.println();
        }
	}

}

Output
 Values: 0
 Values: 1 Values: 2
 Values: 3 Values: 4 Values: 5
 Values: 6 Values: 7 Values: 8 Values: 9
 Values: 10 Values: 11 Values: 12 Values: 13 Values: 14
 
 
 EX:2
 
  public class Arrays {
  public static void main(String[] args) {
  int[] student ={1,2,3,4,5};
		
		int[] student ={1,2,3,4,5};
		
		for(int i=0;i < student.length;i++){
			System.out.print(""+i+" ");
		}
	}
		

}

Output
0 1 2 3 4