#100DaysOfCode – Day 8: Mastering 2D Arrays in Java

#100DaysOfCode – Day 8: Mastering 2D Arrays in Java

Up to this point, we’ve worked with 1D arrays — great for storing lists of items. But what if you want to represent something like:

  • A chess board
  • A student grades table
  • A theater seat layout
  • A game map or pixel grid

That’s when we switch to 2D arrays — a grid-like structure made of rows and columns.

What Is a 2D Array?

In Java, a 2D array is basically an array of arrays. Imagine a table with rows and columns — that's what a 2D array looks like.

Each element is located using two indices:

  • One for the row
  • One for the column

How to Declare a 2D Array

Method 1: Declaration with values

int[][] matrix = {

    {1, 2, 3},

    {4, 5, 6},

    {7, 8, 9}

};

Think of it like this:

sql

Row 0 →  1  2  3 

Row 1 →  4  5  6 

Row 2 →  7  8  9

 Method 2: Declare and assign later

int[][] data = new int[2][3];  // 2 rows, 3 columns

data[0][0] = 10;

data[0][1] = 20;

// and so on...

How to Access Elements

To access a specific cell:

System.out.println(matrix[1][2]); // Output: 6 (row 1, column 2)

Remember: Indexing starts from 0 — not 1!

Looping Through a 2D Array (Nested Loops)

for (int i = 0; i < matrix.length; i++) { // Rows

    for (int j = 0; j < matrix[i].length; j++) { // Columns

        System.out.print(matrix[i][j] + " ");

    }

    System.out.println(); // Newline after each row

}

This prints:

1 2 3 

4 5 6 

7 8 9

matrix.length → number of rows matrix[i].length → number of columns in row i

Real-World Example: Seat Booking System

String[][] seats = {

    {"A1", "A2", "A3"},

    {"B1", "B2", "B3"}

};

 System.out.println("Your seat: " + seats[1][2]);  // Output: B3

Imagine building a cinema app — this is exactly how you’d store seat info!

 

Bonus: Sum All Elements in a 2D Array

int[][] nums = {

    {1, 2, 3},

    {4, 5, 6}

};

int sum = 0;

for (int i = 0; i < nums.length; i++) {

    for (int j = 0; j < nums[i].length; j++) {

        sum += nums[i][j];

    }

}

System.out.println("Total sum: " + sum);

Output: Total sum: 21

 

 Day 8 Challenges:

1. Create a 3x3 grid and fill it with numbers from 1 to 9

2️. Build a tic-tac-toe board using char[][]

3️. Write code to find the maximum value in a 2D array

4️. Calculate row-wise and column-wise sums

Summary:

Today you unlocked a powerful way to work with structured, tabular data in Java. 2D arrays are everywhere — in games, data dashboards, spreadsheets, and more. You now know how to declare, access, loop through, and solve real problems using them.

Tomorrow, we’ll go deeper into array-based algorithms — like searching, row/column sums, and diagonal logic.

Let’s level up our code — one array at a time.

#Day8 #Java #2DArrays #100DaysOfCode #LearnToCode #CodeNewbie #SoftwareEngineer #TechJourney #WomenWhoCode #GitHub #CareerSwitch

 

To view or add a comment, sign in

More articles by Venkata Yekula

Explore content categories