Array -


Array is a collection of similar data elements (or similar data types). In java, array is of Object type. That is array will represent an object.
Array elements are always stored in sequential memory locations. That is, for an integer array, if 1st element is stored at memory location 1000 then 2nd one will be stored at 1004 location and so on.

Types of array -

Array can be categorised into two categories -
1- Single Dimensional Array.
2- Multi Dimensional Array.

1- Single Dimensional Array -

An array which contains only one subscript or dimension is called single dimensional array. Creation of array involve following three steps-
  • Declaring array.
  • Allocating memory to array.
  • Initializing array.
Declaring Array - In java array can be declared in two ways -
   
1st form -    type  array_name[ ];
2nd form -    type [ ] array_name;
Here type can be any valid java data type or object type, array_name can be any valid java identifier that you want to use for your array name.
For example -
int arr[ ];
float numbers[ ];
double [ ] roll;

        
At this step, there will be no physical array in memory. Right now array_name will refer to null and does not contain any value.
Allocating memory to array - Array will came into physical existence after allocating memory to it. And we allocate memory to array using new keyword as follows -
  array_name = new type[array_size];
Here type should be the same as used in declaration and array_size determines the number of elements array can contain and it can be any integer value greater than zero.
For example -
     arr = new int[5];
     numbers = new float[10];
     roll  =  new double[5];
 
The first example will allocate 20 bytes (5*4 = 20) of storage for array - 'arr'. Similarly second one will allocate 40 (10*4 = 40) bytes and third one will allocate 40 (5*8=40) bytes.

We can also combine the above two steps into one as follows -
     int arr[] = new int[5];
     float numbers[] = new float[10]; 
     double[] roll = new double[5]; 

Initializing array - Let us suppose that we have an array a with 5 integer elements -
int a[] = new int[5];
It can be represent in memory like this -

We can initialize an array in two ways -
1st form -
array_name[index] = value;
Example -
    
int[0] = 2;
int[1] = 4;
int[2] = 6; 
int[3] = 8; 
int[4] = 10;
    
2nd form -
type array_name[] = {list of values};
                    Or
    type array_name[] = new type[]{list of values};  
Example -
        int a[] = {2,4,6,8,10};
        int a[] = new int[]{2,4,6,8,10};   // both are same
    
Here array will be big enough to hold the number of elements defined in braces { }. That is, in both the cases an array of 5 int elements will be created and it can be represented in memory as follows -

In java array index always starts from 0. And also we cannot store more values than the size of array, if we try to do that , a runtime exception 'Array Index Out Of Bound' will occur. We can also assign an array into another array as follows -
int arr[] = {1,2,3,4};
int b[];
b = arr;
Now array arr and b will point to the same int object and contain same values.

Accessing Array Elements - We can access array elements by using array index as follows -
int x  = a[2];
The above statement will take the 3rd element (element at 2nd index) of array "a" and assign to variable x. So the value of x will be 6.

Example -

Putting together all the above code, here is the program that create, initialize and access the array.
public class Call {

    public static void main(String[] args) {

        int a[] = new int[5];                               // declaring and allocating memory
        System.out.println("Enter array elements");
        for(int i=0;i<5;i++)                                // Normally we use loop to initialise array.
        {
            a[i] = Integer.parseInt(System.console().readLine());
        }
       for(int i =0;i<5;i++)
       {
           System.out.println(a[i]);
       }
    } 
}

    

Output -

Enter array elements
                 1    2    3   4  5
                 1
                 2
                 3
                 4
                 5
    
Here we have defined an array that can contain 5 integer elements. We use for() loop to initialise array, it will ask the values of array from user and user enters 1 2 3 4 5. Next for() loop will display all elements of array.

length property -

We can find the size of an array by using length property as follows -
array_name.length;
It will return allocated size of array.

Example 1 -

public class Call {

    public static void main(String[] args) {

        int a1[] = new int[5];
        int[] a2 = new int[10];
        double a3[] = {1.1,2.1,3.1,4.1};
        char[] a4 = {'a','b'};
        System.out.println("Length of a1 array = "+ a1.length);
        System.out.println("Length of a2 array = "+ a2.length);
        System.out.println("Length of a3 array = "+ a3.length);
        System.out.println("Length of a4 array = "+ a4.length);
        
    }
}

Output -

Length of a1 array = 5
Length of a2 array = 10
Length of a3 array = 4
Length of a4 array = 2
Note - Keep in mind that the value of length has nothing to do with the number of elements that are actually in use. It only reflects the number of elements that the array is designed to hold.

Example 2 -

public class Call {

    public static void main(String[] args) {

        int a[] = new int[5];
       for(int i=0;i< a.length;i++)
       {
           a[i] = Integer.parseInt(System.console().readLine());
       }
       for(int i =0;i< a.length;i++)
       {
           System.out.println(a[i]);
       }
    }
       
}

for each loop -

This style of for loop is added in jdk1.5. It is mainly used to iterate through the elements of arrays and collections. It is called "for each" because it iterate through each element of array or collection.
Syntax -
  for(data_type:array|collection name)
Here data_type should be of the same type as data type of elements of array or collection. For example if array contains integer type elements then data_type should be integer and if it contains some object type element then data_type should be of that type.

Example -

public class Call {
    public static void main(String[] args) {

      int a[] = {1,2,3,4,5};
        System.out.println("Array elements are :");
        for(int i : a)
        {
            System.out.println(i);
        }
    } 
}

        

Output -

Array elements are :
1
2
3
4
5
Here the statement for(int i : a) will iterate through all the elements of array a one by one and put them one by one in integer variable i and statement System.out.println(i); will print them.

2 - Multidimensional Array -

An array which has more than one dimension is called multidimensional array.
Double Dimensional Array (2D array) - 2D Array is the most general form of multidimensional array. It contains 2 dimensions, first dimension represents the number of rows and second one represents number of columns in each row. It is also called matrix or table. We can declare an array as follows -
data_ type array_name[ ][ ];
Here type can be any valid java data type and array_name will be any valid java identifier. For example -
int arr[ ][ ];
Here we define a 2D array of integers named arr.
A 2D Array can be declared using any of the following forms -
1- data_type  array_name[ ][ ];                  for example - int arr[ ][ ];
2- data_type[ ]  array_name[ ];                  for example - int[ ] arr[ ];
3- data_type[ ][ ]  array_name;                  for example -  int [ ][ ] arr;
All the statements are equivalent; you can use any of them. We can allocate memory to array arr as follows -
arr = new int[3][4];  
This statement define an array arr containing 3 rows and 4 columns and will allocate 48 byte (3*4 = 12(elements)*4 = 48 bytes) of memory storage to array arr. It can be represented as follows -

Here the 1st element will be stored at arr[0][0] location and 2nd element to next location i.e. arr[0][1] and so on.
Initializing 2D Array - We can initialize a 2D Array either one by one or by using a single statement as follows -

Example 1 -

public class Call 
{
 public static void main(String[] args) {

 int arr[][] = new int[2][3];
 System.out.println("Enter array elements");
        
 // Initialising Arry elements one by one
 for(int r=0; r < arr.length; r++)   // arr.length will return the number of rows in arr
 {
  for(int c=0; c < arr[r].length;c++)  // arr[r].length will return the number of columns in each row r.
  {
   arr[r][c] = Integer.parseInt(System.console().readLine());
  }
}
        
// Accessing array elements - 
 for(int r[]: arr)   // It will return and copy a complete row in array r of integers at a time.
 {
  for(int c : r)  // It will return each columns in row r and copy that in c.
  {
   System.out.print(c);
  }
  System.out.println();
 }
        
}
       
}

Note - for accessing the array elements we can either use for each loop style as we use above or we can use simple for loop style as used to initialize array elements.

Example 2

public class Call {

    public static void main(String[] args) {

// Declaring and initialising array
     int arr[ ][ ] = {{1,2,3},   // This will declare an array containing 2 rows and 4 columns.
                      {4,5,6}};
             
        // Accessing array elements - 
        for(int r[]: arr)
        {
            for(int c : r)
            {
                System.out.print(c);
            }
            System.out.println();
        }
    }
 }

    

Jagged Array -

A jagged array is similar to 2D array, but it can contain different number of columns in each row. A jagged array is an array of array whose elements are arrays of different size.
Following is the declaration of jagged array containing 4 elements each of which is a 1D array of integers -
Int arr[ ][ ] = new int[4][ ];  
arr[0] = new int[3];
arr[1] = new int[4];
arr[2] = new int[2];
arr[3] = new int[1];

        

Here array arr contain 4 elements (row), first element is an array arr[0] containing 3 elements (columns) , second element is an array arr[1] containing 4 elements and so on.
We can also declare and initialise a jagged array in single line as follows -
            int arr[][] = {{1,2,3},
                           {4,5,6,7,8},
                           {10,11}};

    
A jagged array arr containing 3 rows, 1st row containing 3 elements, 2nd row containing 4 elements, 3rd row containing 2 elements.

Example -

public class Call {

    public static void main(String[] args) {

     int arr[][] = {{1,2,3},
                   {4,5,6,7,8},
                   {10,11}};
        System.out.println("Array elements are :-");
        
        for(int r=0;r< arr.length;r++)
        {
            for(int c=0;c< arr[r].length;c++)
            {
                System.out.print(arr[r][c]+"  ");
            }
            System.out.println();
        }
    }
       
}

Output -

Array elements are :-
1  2  3  
4  5  6  7  8  
10  11