Java Multi-Dimensional Arrays

Java Multi-Dimensional Arrays (2D Arrays)

A multi-dimensional array is an array of arrays. The most common type is the 2D array, which is similar to a table or matrix.


1. Declaration and Initialization

Syntax:


Or combined:



 

Example 1: 2D Array Declaration and Initialization


 


2. Looping Through a 2D Array

Using nested for loops:


 

📌 Output:

1 2 3
4 5 6
7 8 9

3. Sum of All Elements in 2D Array


 

📌 Output:

Sum of all elements: 45

4. Row-wise Sum


 

📌 Output:

Sum of row 0: 6
Sum of row 1: 15
Sum of row 2: 24

5. Column-wise Sum


 

📌 Output:

Sum of column 0: 12
Sum of column 1: 15
Sum of column 2: 18

6. Real-Life Example: Seat Booking in Theater


 

📌 Output:

[O] [X] [O] [O] [O]
[O] [O] [O] [X] [O]
[O] [O] [O] [O] [O]

🧠 Key Points

  • A 2D array is an array of arrays.

  • Use nested loops to traverse rows and columns.

  • Useful for tables, matrices, grids, seating arrangements, etc.

  • Can also be extended to 3D arrays or higher.

You may also like...