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



Categories: Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: