Array in java



Array is a collection of similar data type elements. The size of the array is fixed. In array elements are stored in an contiguous memory location. Using indexing we can access the array elements. Array index starts with 0,1,2 and so on.








Types of array



  1. One Dimensional array
  2. Multi Dimensional array







1. One Dimensional Array




In One dimentional array, the data storing index format is 0,1,2...N.




Example-1
public class Main
{
      public static void main(String[] args) 
      {
            int a[] = { 1, 2, 3, 4, 5 };

            System.out.println(a[4]);
      }
}


Output



5







Example-2
public class Main
{
      public static void main(String[] args) 
      {
            int [] a = new int [3];

            a[0] = 1;
            a[1] = 2;
            a[2] = 3;

            for(int i=0;i<3;i++) 
            {
                 System.out.println(a[i]);
            }
      }
} 


Output



1
2
3









2. Multi Dimensional Array



In multi dimentional array, the data storing index format is [0][0],[0][1],...[n][n]. The multi dimentional array are mostly used in matrix and graph.




Example-1
public class Main
{
      public static void main(String[] args) 
      {
            int a [][] = {
                              {1, 2, 3},
                              {4, 5, 6},
                              {7, 8, 9}
                          };

            System.out.print(a[0][1]);
       }
}


Output



2







Example-2
public class Main
{
        public static void main(String[] args) 
        {
              int a[][]=new int [5][5];

              a[0][0] = 1;
              a[0][1] = 2;
              a[4][4] = 3;

              System.out.println(a[4][4]);
        }
}


Output



3









Array methods




S.No Method Explain
Array.length This method is used to find the length of the array.
Arrays.sort() This method is used to sort the array elements.
Arrays.equals() This method is used to compare two arrays whether it is equal or not.
System.arraycopy() This method is used to copy all the elements in one array to another array.