Array Initializer Lists
What you'll learn: How to create and populate arrays in a single, compact step using initializer syntax.
The Shortcut You've Been Waiting For
You've learned that creating an array typically involves two steps: declaring it with new and then assigning values to each index. But Java offers a convenient shortcut when you know your array's values upfront—array initializer lists.
The Initializer Syntax
Instead of this lengthy approach:
int[] scores = new int[3];
scores[0] = 95;
scores[1] = 87;
scores[2] = 92;
You can do this:
int[] scores = {95, 87, 92};
The compiler automatically determines the array length (3 in this case) and assigns each value to consecutive indices. No new keyword needed—Java handles it behind the scenes.
When to Use Initializer Lists
This syntax shines when you have a fixed, known set of values:
String[] days = {"Monday", "Tuesday", "Wednesday"};
boolean[] flags = {true, false, true, true};
double[] prices = {19.99, 5.50, 12.75};
Important limitation: Initializer lists only work during declaration. You cannot use this syntax later to reassign the array:
int[] numbers;
numbers = {1, 2, 3}; // Compiler error!
If you need to create an anonymous array after declaration, you must use new int[]{1, 2, 3}.
Why This Matters
Initializer lists make your code cleaner and more readable, especially for small, constant arrays. They eliminate boilerplate while making your intent crystal-clear: "Here's an array with exactly these values."
Key Takeaway: Use curly braces {value1, value2, value3} during array declaration to create and populate an array in one concise step—Java infers the size automatically.