Quantcast
Viewing all articles
Browse latest Browse all 168

Different ways of declaration and initialization of arrays in Java

The below code shows the different ways one can declare and initialize an Array in Java:

import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {
        int[] a1 = new int[]{1,2,3,4};
        print(a1); //[1,2,3,4]
        
        int[] a2 = new int[4];
        a2[0] = 1;a2[2]=10;
        print(a2); //[1,0,10,0]

        int[] a3 = {1,4,5,67,8};
        print(a3); //[1,4,5,67,8]

        print(getArray()); //[3,32,6,7,5]
    }

    public static int[] getArray(){
        //return {1,2,3,4}; - Invalid
        return new int[]{3,32,6,7,5};
    }

    public static void print(int[] a){
        System.out.println(Arrays.toString(a));
    }
}
  • Line 5: Declaration of array along with initialization of its values. Here it is not required to pass the size of the array.
  • Line 8-9: Declaration of array by providing its size. The array will be initialized with 0 and we can then assign the value using the index.
  • Line 12: Declaration with initialization
  • Line 20: One of permissible way to return an array from the method


Viewing all articles
Browse latest Browse all 168

Trending Articles