Unit 8: 2D Arrays

Creating 2D Arrays in Java

Introduction to 2D Arrays in Java

In Java, 2D arrays provide a way to store table-like data where you have rows and columns. They're essentially an "array of arrays", allowing for a grid of values, be it numbers, strings, or objects. This lesson will guide you through the creation, declaration, and initialization of 2D arrays.


Basics of 2D Arrays

Declaration

To declare a 2D array, use two sets of square brackets:

int[][] matrix;

Initialization

Initializing a 2D array involves specifying the size for rows and possibly columns:

matrix = new int[3][4]; // 3 rows and 4 columns

Allocation of Rows

2D arrays in Java can have rows of varying lengths, making them "jagged":

matrix = new int[3][]; // Only rows are specified
matrix[0] = new int[3];
matrix[1] = new int[5];
matrix[2] = new int[4];

Deep Dive

2D arrays can be more than just 2 levels deep! Java supports multi-dimensional arrays, though they're less common. You could have int[][][] cube = new int[3][4][5] to represent a 3x4x5 cube.


Populating a 2D Array

Once you've declared and initialized your 2D array, you can populate it with values:

matrix[0][1] = 42; // set the value at first row and second column to 42

For filling the entire array, nested loops come in handy:

for(int i = 0; i < matrix.length; i++) {
    for(int j = 0; j < matrix[i].length; j++) {
        matrix[i][j] = i * j; // just a sample computation
    }
}

Summary

Creating 2D arrays in Java is a foundational skill for any budding Java programmer. They allow for structured data storage and manipulation, paving the way for advanced algorithms, game boards, graphics, and more. Remember the difference between declaring and initializing, and always be mindful of the array's boundaries.


References


AP CSA Homework Assignment

Assignment: Build Your Chessboard

Instructions

  1. Create a Java class named Chessboard.
  2. Declare a 2D array of size 8x8, representing a standard chess board.
  3. Populate the array with initial positions of chess pieces (e.g., 'R' for rook, 'P' for pawn). For simplicity, you can use the first letter of each piece and 'E' for empty.
  4. Implement a method to print the board to the console.
  5. In your main method, demonstrate the board's initial state.
  6. Bonus: Implement methods to move pieces on the board (consider only straight moves for pawns).
Previous
Autoboxing and Unboxing