๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Multi-Dimensional Array (2D)  


Introduction
  • A 2D array is an example of a multi-dimensional array, which can have more than one dimension.
  • It is an array of arrays which stores the data in a table-like structure with rows and columns.
  • It is often used to represent matrices, grids, or tabular data such as marks of students in different subjects or seating arrangements in a theater.
  • For example :
    • int[][] numbers = {
          {10, 20, 30},
          {40, 50, 60}
      };
    • Multi Dimensional Array 2D in Java

Working with 2D Arrays:

  • To work with 2D arrays in Java, we need to learn the following steps:
    1. Declare an array - Define the reference of the array with a specific data type.
    2. Create an array - Allocate memory for the array using the new keyword.
    3. Initialize an array - Assign values to the elements of the array.
    4. Retrieve elements of an array - Access array elements using their index.
  • We will go through each step with examples below.
1. Declare a 2D Array
  • Array declaration is the process of defining a variable that can hold multiple values of the same data type.
  • It tells the compiler what type of data the array will store (int, float, String, etc.).
  • At this stage, memory is not allocated; only the reference for the array is declared.
  • How to Declare a 2D Array (Commonly Used Syntax):
    • Syntax:
      dataType[][] arrayName;
    • Example:
      int[][] numbers;
  • Alternate Syntaxes to Declare a 2D Array:
    • Syntax:
      dataType arrayName[][];
      dataType [][]arrayName;
    • Examples:
      int numbers[][];
      int [][]numers;
2. Create a 2D Array
  • Array creation is the process of allocating memory for the array after it has been declared.
  • This is done using the new keyword in Java.
  • At this stage, a fixed block of memory is reserved to store multiple elements of the specified data type.
  • The size of the array must be defined during creation (it cannot be changed later).
  • How to Create a 2D Array:
    • Syntax:
      arrayName = new dataType[rows][columns];
    • Example:
      numbers = new int[2][3];
3. Initialize a 2D Array
  • Array initialization is the process of assigning values to the elements of a 2D array.
  • After a 2D array is created, its elements have default values (e.g., 0 for int, 0.0 for float, null for objects).
  • How to Initialize a 2D Array:
    • Syntax:
      arrayName[rowIndex][columnIndex] = value;
    • Examples:
      int[][] numbers = new int[2][3];
      
      numbers[0][0] = 10;
      numbers[0][1] = 20;
      numbers[0][2] = 30;
      numbers[1][0] = 40;
      numbers[1][1] = 50;
      numbers[1][2] = 60;
4. Retrieve Elements of a 2D Array
  • Retrieving elements from a 2D array means accessing the values stored in the array using their row and column indices.
  • 2D array elements in Java are zero-indexed, so the first element is at index [0][0] and the last element is at index [rows-1][columns-1].
  • Different Ways to Retrieve Elements of a 2D Array
    1. Using Row and Column Index:
      • int[][] numbers = {
            {10, 20, 30},
            {40, 50, 60}
        };
        
        System.out.println(numbers[0][1]);  // Output: 20
        System.out.println(numbers[1][2]);  // Output: 60
    2. Using Nested For Loop:
      • for(int i = 0; i < numbers.length; i++)
        {
            for(int j = 0; j < numbers[i].length; j++)
            {
                System.out.println(numbers[i][j]);
            }
        }
    3. Using Enhanced For Loop (For-Each):
      • for(int[] row : numbers)
        {
            for(int num : row)
            {
                System.out.println(num);
            }
        }

2D Array Programs:-
  • Program 1:
    public class MainApp1
    {
        public static void main(String[] args)
        {
            // 1. Declare and create a 2D array of size 2x3
            int[][] numbers = new int[2][3];
    
            // 2. Initialize array elements
            numbers[0][0] = 10;
            numbers[0][1] = 20;
            numbers[0][2] = 30;
            numbers[1][0] = 40;
            numbers[1][1] = 50;
            numbers[1][2] = 60;
    
            // 3. Access and print array elements using nested for loop (Way 1)
            System.out.println("Way 1:");
            for (int i = 0; i < numbers.length; i++)
            {
                for (int j = 0; j < numbers[i].length; j++)
                {
                    System.out.print(numbers[i][j] + " ");
                }
                System.out.println(); // Move to next row
            }
    
            // 4. Access and print array elements using nested for-each loop (Way 2)
            System.out.println("Way 2:");
            for (int[] row : numbers)
            {
                for (int num : row)
                {
                    System.out.print(num + " ");
                }
                System.out.println(); // Move to next row
            }
        }
    }
    • Points to note:
      • We have accessed the 2D array elements in 2 ways: using nested for loop and nested for-each loop. The nested for-each loop is preferred as it is simpler and easier to understand.
      • Declaring, creating, and initializing the array element by element is lengthy. We can also declare, create, and initialize the array in a single line using shorthand notation.
  • Program 2:
    public class MainApp2
    {
        public static void main(String[] args)
        {
            // 1. Declare, create, and initialize a 2D array in a single line
            int[][] numbers = {
                {10, 20, 30},
                {40, 50, 60}
            };
    
            // 2. Access and print array elements using nested for-each loop
            System.out.println("Numbers are:");
            for (int[] row : numbers)
            {
                for (int num : row)
                {
                    System.out.print(num + " ");
                }
                System.out.println(); // Move to next row
            }
        }
    }
    • Points to note:
      • In this program, we have declared, created, and initialized the 2D array in a single line using shorthand notation.
      • We accessed the elements using a nested for-each loop, which is the preferred way for 2D arrays.