00:00

Anonymous Array in Java – Explained with Examples

An anonymous array is an array created without being stored in a named variable. You write it right where it is needed, typically as a method argument: sum(new int[] {10, 20, 30}). It is a convenient way to pass a small, one-off set of values.

This tutorial explains the syntax of anonymous arrays, where you can use them, how they differ from array initializers and varargs, and their limitations.

1. Syntax

Anonymous array syntax
new dataType[] {value1, value2, value3}

new int[] {10, 20, 30}
new String[] {"red", "green"}
new int[][] {{1, 2}, {3, 4}}
  • Do not put a size inside the brackets; the size comes from the number of values. new int[3] {1, 2, 3} is a compile error.
  • The array is a normal array object; it just has no variable name.
  • If nothing keeps a reference to it after use, it becomes eligible for garbage collection.

2. Using Anonymous Arrays

AnonymousArrayBasics.java
import java.util.Arrays;

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

    static void printNames(String[] names) {
        System.out.println(String.join(", ", names));
    }

    public static void main(String[] args) {
        // Anonymous arrays: created and passed without a variable name
        System.out.println("sum = " + sum(new int[] {10, 20, 30, 40}));
        printNames(new String[] {"Asha", "Ravi", "Meera"});

        // Used directly in a for-each loop
        for (char c : new char[] {'J', 'A', 'V', 'A'}) System.out.print(c);
        System.out.println();

        // A two-dimensional anonymous array
        System.out.println(Arrays.deepToString(new int[][] {{1, 2}, {3, 4}}));

        // Its length is known from the values
        System.out.println("length = " + new double[] {1.5, 2.5, 3.5}.length);
    }
}
Output
sum = 100
Asha, Ravi, Meera
JAVA
[[1, 2], [3, 4]]
length = 3

Anonymous arrays work anywhere an array value is expected: as method arguments, in for-each loops, and even to read a property like length directly.

3. Returning and Reassigning Arrays

The short form {90, 80} (an array initializer) is only allowed when you declare a variable. Everywhere else, such as in a return statement or when reassigning a variable, you need the full anonymous array syntax:

ReturnAndAssign.java
import java.util.Arrays;

public class ReturnAndAssign {
    static String[] weekend() {
        return new String[] {"Saturday", "Sunday"};      // return an anonymous array
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(weekend()));

        int[] scores;
        // scores = {90, 80};                          // compile error: initializer only allowed in a declaration
        scores = new int[] {90, 80};                     // anonymous array works anywhere
        System.out.println(Arrays.toString(scores));

        scores = new int[] {70, 60, 50};                 // reassign to a different array
        System.out.println(Arrays.toString(scores));
    }
}
Output
[Saturday, Sunday]
[90, 80]
[70, 60, 50]
SyntaxAllowed where
int[] a = {1, 2};Only in a declaration
new int[] {1, 2}Anywhere an expression is allowed: arguments, returns, assignments

4. Anonymous Arrays vs Varargs

Before Java 5, anonymous arrays were the usual way to pass a variable number of values. Varargs (int... values) now let callers list the values directly, and the compiler creates the array for them. A varargs method still accepts an explicit array too:

AnonymousVsVarargs.java
public class AnonymousVsVarargs {
    static int maxOf(int[] values) {                     // needs an array argument
        int m = values[0];
        for (int v : values) m = Math.max(m, v);
        return m;
    }

    static int maxOfVarargs(int... values) {             // varargs: the compiler builds the array
        int m = values[0];
        for (int v : values) m = Math.max(m, v);
        return m;
    }

    public static void main(String[] args) {
        System.out.println(maxOf(new int[] {4, 9, 2}));      // anonymous array required
        System.out.println(maxOfVarargs(4, 9, 2));            // no array syntax needed
        System.out.println(maxOfVarargs(new int[] {7, 3}));   // varargs also accept an array
    }
}
Output
9
9
7

Use varargs in new APIs you design; use anonymous arrays when calling methods that take an array parameter. Learn more in Varargs in Java.

5. Other Common Uses

Typical anonymous arrays in real code
List<String> names = Arrays.asList(new String[] {"a", "b"});   // (Arrays.asList("a", "b") is shorter)
int max = Arrays.stream(new int[] {3, 9, 4}).max().getAsInt();
String[] parts = list.toArray(new String[0]);                  // zero-length array as a type hint
Object[] row = new Object[] {"Asha", 30, true};                // mixed values for a table row

6. Limitations

  • You cannot refer to the array again later unless something stores its reference.
  • For larger or reused data, a named variable or a constant is clearer.
  • It cannot be used with var without the new part: var a = {1, 2}; does not compile, but var a = new int[] {1, 2}; does.

7. Summary

  • An anonymous array is created with new type[] {values} and has no variable name.
  • Its size comes from the values; never put a size in the brackets.
  • It can be used anywhere an array expression is allowed, unlike the short {...} initializer.
  • Varargs make many anonymous arrays unnecessary in modern APIs.

Related Tutorials