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
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
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);
}
}
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:
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));
}
}
[Saturday, Sunday] [90, 80] [70, 60, 50]
| Syntax | Allowed 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:
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
}
}
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
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
varwithout thenewpart:var a = {1, 2};does not compile, butvar 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
Frequently Asked Questions (FAQ)
Q1. What is an anonymous array in Java?
An array created with new type[] {values} without assigning it to a named variable, typically passed straight to a method.
Q2. Why is it called anonymous?
Because it has no name: no variable refers to it in your code. It exists only where it is created and used.
Q3. Can I specify the size of an anonymous array?
No. The size is determined by the number of values. new int[3] {1, 2, 3} is a compile error.
Q4. What is the difference between an anonymous array and an array initializer?
An initializer {1, 2} can only be used in a declaration such as int[] a = {1, 2};. An anonymous array new int[] {1, 2} can be used anywhere an expression is allowed.
Q5. Can an anonymous array be multidimensional?
Yes: new int[][] {{1, 2}, {3, 4}}. Rows may even have different lengths.
Q6. Can I return an anonymous array from a method?
Yes: return new String[] {"Saturday", "Sunday"};. A plain return {...}; does not compile.
Q7. Is an anonymous array garbage collected?
Yes, once no reference to it remains, like any other object. If a method stores the reference, the array stays alive as long as that reference does.
Q8. When should I use an anonymous array?
When you need to pass a small, fixed set of values to a method that takes an array, especially for one-off calls.
Q9. What is the difference between anonymous arrays and varargs?
With an anonymous array, the caller creates the array explicitly. With varargs, the caller lists values and the compiler creates the array. Varargs methods also accept anonymous arrays.
Q10. Can anonymous arrays contain objects?
Yes: new Student[] {new Student("Asha"), new Student("Ravi")}.
Q11. Can I modify an anonymous array?
Yes, the method receiving it can change its elements, but since the caller has no reference, those changes are invisible to the caller.
Q12. Can an anonymous array be empty?
Yes: new int[] {} creates an array of length 0.
Q13. Can I use var with an anonymous array?
Yes: var a = new int[] {1, 2};. Then it is no longer anonymous, because a names it.
Q14. Where are anonymous arrays stored?
On the heap, like all arrays. Only the lack of a named variable makes them different.
Q15. Is there a performance difference compared with named arrays?
No. The same array object is created; naming it or not makes no difference at runtime.
Q16. Can I pass an anonymous array to a method expecting a List?
Not directly. Convert it, for example Arrays.asList(new String[] {"a", "b"}), or simply use List.of("a", "b").
Q17. Why does list.toArray(new String[0]) use an empty anonymous array?
The empty array tells toArray which array type to create. Since Java 11, list.toArray(String[]::new) is an alternative.
Q18. Can an anonymous array hold mixed types?
Only if its element type allows it, for example new Object[] {"Asha", 30, true}.
Q19. Do anonymous arrays have a length?
Yes, every array does. new int[] {1, 2, 3}.length is 3.
Q20. Are anonymous arrays and anonymous classes related?
Only by name. Both are created without a name, but anonymous classes are class definitions with a body, while anonymous arrays are ordinary arrays.