Unit 8: 2D Arrays

This unit covers two-dimensional arrays, their creation, manipulation, and common operations in Java programming.

Key Concepts

  • 2D Array Declaration: Creating and initializing 2D arrays
  • 2D Array Access: Reading and writing elements
  • 2D Array Traversal: Row-major and column-major traversal
  • 2D Array Algorithms: Common operations and patterns
  • 2D Array as Parameters: Passing 2D arrays to methods
  • Ragged Arrays: Understanding non-rectangular arrays
  • Matrix Operations: Basic matrix manipulations

Example Code


// Example: Working with 2D Arrays in Java
public class TwoDArrayExample {
  public static void main(String[] args) {
    // Create a 2D array
    int[][] matrix = new int[3][3];
    
    // Initialize with values
    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        matrix[i][j] = i + j;
      }
    }
    
    // Print the matrix
    for (int i = 0; i < matrix.length; i++) {
      for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
      }
      System.out.println();
    }
  }
}
              

Interactive Code Playground

Try out your own 2D array code here!

Output:
Note: This is a simulated environment. For actual Java code execution, please use an IDE or online Java compiler.

For actual code execution, we recommend using:

Multiple Choice Quiz

Question 1: 2D Array Declaration

Which of the following correctly declares a 2D array of integers with 3 rows and 4 columns?

int[][] arr = new int[3][4];
int arr[][] = new int[4][3];
int[] arr[] = new int[3,4];
int arr = new int[3][4];
The correct answer is A. In Java, 2D arrays are declared with the syntax int[][] arr = new int[rows][columns].
Question 2: Ragged Arrays

What is a ragged array?

A 2D array where each row has a different length
A 2D array with missing elements
A 2D array with null values
A 2D array with duplicate values
The correct answer is A. A ragged array is a 2D array where each row can have a different number of columns.
Question 3: 2D Array Traversal

What is the correct way to traverse a 2D array?

Using nested for loops
Using a single for loop
Using a while loop
Using a do-while loop
The correct answer is A. 2D arrays are typically traversed using nested for loops, with the outer loop iterating through rows and the inner loop through columns.

Practice Problems

  1. Write a program that rotates a 2D array 90 degrees clockwise.
  2. Implement a method that checks if a 2D array is symmetric.
  3. Create a program that finds the largest sum of any row in a 2D array.

Tips for Success

  • Remember that 2D arrays are arrays of arrays.
  • Use nested loops for traversal.
  • Be careful with array bounds in both dimensions.
  • Consider using enhanced for loops when possible.
  • Pay attention to row-major vs column-major traversal.