Image

Java - Core Java - Array

Array

Array is a referenced type of data type in java, it is used to create fixed number of multiple variables of same type to store multiple values of similar type in contiguous memory locations with single variable name. In java following are the important points in java:

  • All arrays are dynamically allocated in java.
  • The size of an array must be specified by an int.
  • The variables in the array are ordered and each element’s index is started from 0.
  • Every array type implements the interface Cloneable and Serializable.
  • Arrays are objects in java, we can find their length using member length.
  • Array variable can also be declared like other variables with [] after the data type
  • Java array can also be used as a static field, a local variable or a method parameter.
  • The direct superclass of an array type is Object. 1567067110-array.jpg

    Need of Array

    In java array is used to collect similar type of values or objects to send all those multiple values with single call from one method to another methods either as an argument or as a return value.

    Limitation of Array

    Array size is fixed, means we cannot increase or decrease its size after its creation.

    Types of Array

    There are two types of array in java
    1. One-Dimensional Arrays
    2. Multi-Dimensional Arrays

    One-Dimensional Arrays

    Ex: int arr[]=new int[5];
    
    class ArrayDemoc
    {
        public static void main (String[] args) 
        {         
          // declares an Array of integers.
          int[] arr;         
          // allocating memory for 5 integers.
          arr = new int[5];
          // initialize the elements of the array
          arr[0] = 10;
          arr[1] = 20;
          arr[2] = 30;
          arr[3] = 40;
          arr[4] = 50;
          // accessing the elements
          for (int i = 0; i < arr.length; i++)
             System.out.println("Element at index " + i +   " : "+ arr[i]);          
        }
    }
    O/P
    Element at index 0 : 10
    Element at index 1 : 20
    Element at index 2 : 30
    Element at index 3 : 40
    Element at index 4 : 50

    Multi-Dimensional Arrays

    > By specifying [] more than once we can achieve multi dimensional array.
    Ex: int arr[][]=new int[5][5];
    
    class MultiArrayDemo
    {
        public static void main(String args[])
        {
            // declaring and initializing 2D array
            int arr[][] = { {1,2,3},{4,6,5},{8,5,6} };
            // printing 2D array
            for (int i=0; i< 3 ; i++)
            {
                for (int j=0; j < 3 ; j++){
                    System.out.print(arr[i][j] + " ");
             }
                System.out.println();
            }
        }
    }
    O/P
    1 2 3
    4 6 5
    8 5 6