BCA / B.Tech 8 min read

Anonymous Arrays in Java

What is an Anonymous Array in Java?

An anonymous array is an array created without an explicit reference variable (a name). It is created, initialized, and used in a single expression. This is useful for one-time situations where you need to create and use an array immediately, such as passing it as an argument to a method, without the need to declare a separate variable for it.

Syntax:

You define an anonymous array with the new keyword, followed by the type, square brackets [], and the elements enclosed in curly braces {}.

new <data_type>[] {element1, element2, ...};


Common Use Case: Passing to a Method

Imagine you have a method that calculates the sum of integers in an array.


public static int sum(int[] numbers) {
    int total = 0;
    for (int num : numbers) {
        total += num;
    }
    return total;
}

public static void main(String[] args) {
    // Instead of creating a named array first:
    // int[] myNumbers = {10, 20, 30};
    // int result = sum(myNumbers);

    // We can call the method directly with an anonymous array:
    int result = sum(new int[]{10, 20, 30}); 
    
    System.out.println("The sum is: " + result); // Prints "The sum is: 60"
}
        

Benefits and Limitations:
  • Benefit (Conciseness): It reduces code verbosity by avoiding the need for a temporary array variable.
  • Limitation (One-time Use): Since the array has no name, you cannot refer to it again after the expression in which it was created is executed.