Array declaration, creation and initialisation in a single line

Array declaration, creation and initialisation in multiple lines:

import java.lang.*;

class Test {
    public static void main(String[] args) {
        int[] x; // array declaration
        x = new int[3]; // array creation
        x[0] = 10; // array initialisation
        x[1] = 20; // array initialisation
        x[2] = 30; // array initialisation
    }
}

Array declaration, creation and initialisation in a single line:

import java.lang.*;

class Test {
    public static void main(String[] args) {
        int[] x = {10,20,30};
        char[] ch = {'a','e','i','o','u'};
        String[] str = {"A","AA","AAA"};
    }
}

We can declare, create and initialise an array in a single line (shortcut representation)

2D Array declaration, creation and initialisation in a single line:

Diagram illustrating how array of arrays style representation is efficient at memory utilisation
Diagram illustrating how array of arrays style representation is efficient at memory utilisation.
import java.lang.*;

 class Test {
     public static void main(String[] args) {
          int[][] x = {
              {10,20,30,40,50}
              ,{20,40}
              ,{30}
              ,{10,50,20}
          };
     }
 }

The shortcut representation can also be used to for multi-dimensional arrays.

3D Array declaration, creation and initialisation in a single line:

Diagram illustrating array of arrays style representation for 3d array.
Diagram illustrating array of arrays style representation for 3d array.
import java.lang.*;

class Test {
    public static void main(String[] args) {
          int[][] x = {
              {
                {0}
                ,{0,0}
                ,{0,0,0}
              }
              ,{
                {0,0}
                ,{0,0}
              }
          };
    }
}

To use this shortcut, it is compulsory to perform declaration, initialisation and creation in a single line.

import java.lang.*;

  class Test {
      public static void main(String[] args) {
            int[] a = {10,20,30}; // VALID
            int[] b;
            b = {10,20,30}; // INVALID: compile-time error - illegal start of expression
      }
  }

The example above shows that trying to split the shortcut in multiple line does not work. The compiler will throw a compile-time error.