Anonymous Array Creation
You'll learn how to pass an array directly to a method without first storing it in a variable.
What Is Anonymous Array Creation?
Sometimes you need to pass an array to a method, but you'll never use that array again. Instead of declaring a variable, storing the array, and then passing it, Java lets you create the array on the spot as part of the method call itself. This is called anonymous array creation because the array has no name—it's created and used immediately.
The Syntax
You've already learned array initializer lists like {1, 2, 3}, but those only work during declaration. To create an anonymous array anywhere else, use this syntax:
new int[]{1, 2, 3}
Notice you must include new int[] before the values in curly braces. This creates an int array with three elements and passes it directly.
Using It with Method Calls
Imagine you have a method that prints array elements:
public static void printValues(int[] numbers) {
for (int num : numbers) {
System.out.print(num + " ");
}
}
Instead of:
int[] data = {5, 10, 15};
printValues(data); // passing named array
You can do:
printValues(new int[]{5, 10, 15}); // anonymous array
The array is created, passed, and used—all in one line. No variable needed.
Why Use It?
It's cleaner when you only need the array once. Think of it like handing someone a disposable coffee cup versus giving them a named mug—sometimes disposable is perfectly fine.
Key Takeaway: Use new Type[]{elements} to create and pass arrays directly to methods without declaring a variable—perfect for one-time use.