Site icon Experiences Unlimited

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){

Exit mobile version