Initializing 2D Arrays with Literals
You'll learn how to create and fill a two-dimensional array in one compact statement using nested curly braces.
What You Already Know
You've learned how to declare and create 2D arrays, but initializing them element-by-element can be tedious. Just like you used initializer lists with single arrays, Java lets you populate an entire 2D array when you create it—using a special nested syntax.
The Core Concept
When initializing a 2D array with literal values, you use nested curly braces. The outer braces contain rows, and each inner brace contains the elements for that row. Think of it like building a spreadsheet: the outer braces define the table itself, while each inner brace defines one complete row of data.
Here's the basic syntax:
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
This creates a 3×3 array where grid[0][0] equals 1, grid[0][1] equals 2, and so on. Each inner array is a row.
Breaking It Down
- The outer braces
{ ... }surround the entire 2D structure - Each inner brace pair
{1, 2, 3}represents one row - Rows are separated by commas
- You don't need to specify dimensions with
newwhen using this syntax
You can also format it on one line for smaller arrays:
int[][] matrix = {{1, 2}, {3, 4}};
This creates a 2×2 array immediately, fully populated and ready to use.
Why This Matters
Initializing with literals is perfect for test data, fixed lookup tables, or small known datasets—it's readable and efficient.
Key Takeaway: Use nested curly braces to initialize 2D arrays with literal values—outer braces contain rows, inner braces contain each row's elements.