Anonymous arrays

We can sometimes declare an array without a name, these type of nameless arrays are called anonymous arrays. The main purpose of anonymous arrays is just for instant use (one time usage).

We can create an anonymous arrays as follows: new int[]{10,20,30,40}. When creating anonymous arrays, size of the array must not be specified, otherwise there it will be an compile-time error.

import java.lang.*;

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

    public static void sum(int[] arr) {
      int total = 0;
      for(int val : arr) {
          total = total + val;
      }
      System.out.println("The sum is:" + total);
    }
}

When creating anonymous arrays, the size of the array must not be specified, otherwise the compiler will throw a compile-time error.

In the example above, an array was required to call the sum(int[] arr) method. After completing the sum(int[] arr) method call, the array is no longer being used. Hence for this one time requirement, an anonymous array is the best choice.

import java.lang.*;

class Test {
    public static void main(String[] args) {
        sum(new int[]{10,20,30,40}); // VALID
        sum(new int[4]{10,20,30,40}); // INVALID
    }

    public static void sum(int[] arr) {
      int total = 0;
      for(int val : arr) {
          total = total + val;
      }
      System.out.println("The sum is:" + total);
    }
}

Anonymous arrays concept can also be applied to multi-dimensional arrays:

import java.lang.*;

class Test {
    public static void main(String[] args) {
        sum(new int[][]{{10,20},{30,40,50}}); // VALID
    }

    public static void sum(int[][] arr) {
        int total = 0;
        for(int[] subArr : arr) {
            for(int val : subArr) {
                total = total + val;
            }
        }
        System.out.println("The sum is:" + total);
    }
}

Depending on requirements, a name can also be assigned to an anonymous array, doing so however means it is no longer anonymous:

import java.lang.*;

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

    public static void sum(int[][] arr) {
        int total = 0;
        for(int[] subArr : arr) {
            for(int val : subArr) {
                total = total + val;
            }
        }
        System.out.println("The sum is:" + total);
    }
}