Arrays & Collections
2D Arrays
Grids and Tables
You're building a seating chart for a theater. Each seat has a row and column. A 2D array lets you store and access data by two coordinates - perfect for grids, game boards, and spreadsheets.
Create a seating chart
Initialize a 2D array to represent a grid of seats.
public class CreateGrid {
public static void main(String[] args) {
// Theater seating chart: rows x seats per row
int rows = ;
int cols = ;
// Create 2D array for seat numbers
int[][] seating = new int[rows][cols];
// Assign seat numbers (1, 2, 3, ...)
int seatNumber = 1;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
seating[row][col] = seatNumber;
seatNumber++;
}
}
// Display the seating chart
System.out.println("=== Theater Seating Chart ===");
for (int row = 0; row < rows; row++) {
System.out.print("Row " + (row + 1) + ": ");
for (int col = 0; col < cols; col++) {
System.out.print(seating[row][col] + "\t");
}
System.out.println();
}
int totalSeats = rows * cols;
System.out.println("Total seats: " + totalSeats);
}
}
public class CreateGrid {
public static void main(String[] args) {
// Theater seating chart: rows x seats per row
int rows = ;
int cols = ;
// Create 2D array for seat numbers
int[][] seating = new int[rows][cols];
// Assign seat numbers (1, 2, 3, ...)
int seatNumber = 1;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
seating[row][col] = seatNumber;
seatNumber++;
}
}
// Display the seating chart
System.out.println("=== Theater Seating Chart ===");
for (int row = 0; row < rows; row++) {
System.out.print("Row " + (row + 1) + ": ");
for (int col = 0; col < cols; col++) {
System.out.print(seating[row][col] + "\t");
}
System.out.println();
}
int totalSeats = rows * cols;
System.out.println("Total seats: " + totalSeats);
}
}
public class CreateGrid {
public static void main(String[] args) {
// Theater seating chart: rows x seats per row
int rows = ;
int cols = ;
// Create 2D array for seat numbers
int[][] seating = new int[rows][cols];
// Assign seat numbers (1, 2, 3, ...)
int seatNumber = 1;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
seating[row][col] = seatNumber;
seatNumber++;
}
}
// Display the seating chart
System.out.println("=== Theater Seating Chart ===");
for (int row = 0; row < rows; row++) {
System.out.print("Row " + (row + 1) + ": ");
for (int col = 0; col < cols; col++) {
System.out.print(seating[row][col] + "\t");
}
System.out.println();
}
int totalSeats = rows * cols;
System.out.println("Total seats: " + totalSeats);
}
}
public class CreateGrid {
public static void main(String[] args) {
// Theater seating chart: rows x seats per row
int rows = ;
int cols = ;
// Create 2D array for seat numbers
int[][] seating = new int[rows][cols];
// Assign seat numbers (1, 2, 3, ...)
int seatNumber = 1;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
seating[row][col] = seatNumber;
seatNumber++;
}
}
// Display the seating chart
System.out.println("=== Theater Seating Chart ===");
for (int row = 0; row < rows; row++) {
System.out.print("Row " + (row + 1) + ": ");
for (int col = 0; col < cols; col++) {
System.out.print(seating[row][col] + "\t");
}
System.out.println();
}
int totalSeats = rows * cols;
System.out.println("Total seats: " + totalSeats);
}
}
A 2D array is an "array of arrays". Declare with int[][] grid = new int[rows][cols].
@concept 2D array
Array of arrays: int[][] grid. Access with grid[row][col].
Access a specific seat
Look up a value using row and column indices.
public class AccessElement {
public static void main(String[] args) {
// Ticket prices by section (rows) and day (columns)
// Rows: 0=Front, 1=Middle, 2=Back
// Cols: 0=Mon, 1=Tue, 2=Wed, 3=Thu, 4=Fri
int[][] prices = {
{50, 50, 55, 55, 75}, // Front row
{40, 40, 45, 45, 60}, // Middle row
{25, 25, 30, 30, 45} // Back row
};
// Customer wants: middle section, Friday
int wantRow = ;
int wantCol = ;
int price = prices[wantRow][wantCol];
String[] sections = {"Front", "Middle", "Back"};
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
System.out.println("=== Ticket Lookup ===");
System.out.println("Section: " + sections[wantRow]);
System.out.println("Day: " + days[wantCol]);
System.out.println("Price: $" + price);
// Show full price chart
System.out.println("\n=== Full Price Chart ===");
System.out.print(" ");
for (String day : days) {
System.out.print(day.substring(0, 3) + "\t");
}
System.out.println();
for (int r = 0; r < prices.length; r++) {
System.out.print(sections[r] + "\t");
for (int c = 0; c < prices[r].length; c++) {
System.out.print("$" + prices[r][c] + "\t");
}
System.out.println();
}
}
}
public class AccessElement {
public static void main(String[] args) {
// Ticket prices by section (rows) and day (columns)
// Rows: 0=Front, 1=Middle, 2=Back
// Cols: 0=Mon, 1=Tue, 2=Wed, 3=Thu, 4=Fri
int[][] prices = {
{50, 50, 55, 55, 75}, // Front row
{40, 40, 45, 45, 60}, // Middle row
{25, 25, 30, 30, 45} // Back row
};
// Customer wants: middle section, Friday
int wantRow = ;
int wantCol = ;
int price = prices[wantRow][wantCol];
String[] sections = {"Front", "Middle", "Back"};
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
System.out.println("=== Ticket Lookup ===");
System.out.println("Section: " + sections[wantRow]);
System.out.println("Day: " + days[wantCol]);
System.out.println("Price: $" + price);
// Show full price chart
System.out.println("\n=== Full Price Chart ===");
System.out.print(" ");
for (String day : days) {
System.out.print(day.substring(0, 3) + "\t");
}
System.out.println();
for (int r = 0; r < prices.length; r++) {
System.out.print(sections[r] + "\t");
for (int c = 0; c < prices[r].length; c++) {
System.out.print("$" + prices[r][c] + "\t");
}
System.out.println();
}
}
}
public class AccessElement {
public static void main(String[] args) {
// Ticket prices by section (rows) and day (columns)
// Rows: 0=Front, 1=Middle, 2=Back
// Cols: 0=Mon, 1=Tue, 2=Wed, 3=Thu, 4=Fri
int[][] prices = {
{50, 50, 55, 55, 75}, // Front row
{40, 40, 45, 45, 60}, // Middle row
{25, 25, 30, 30, 45} // Back row
};
// Customer wants: middle section, Friday
int wantRow = ;
int wantCol = ;
int price = prices[wantRow][wantCol];
String[] sections = {"Front", "Middle", "Back"};
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
System.out.println("=== Ticket Lookup ===");
System.out.println("Section: " + sections[wantRow]);
System.out.println("Day: " + days[wantCol]);
System.out.println("Price: $" + price);
// Show full price chart
System.out.println("\n=== Full Price Chart ===");
System.out.print(" ");
for (String day : days) {
System.out.print(day.substring(0, 3) + "\t");
}
System.out.println();
for (int r = 0; r < prices.length; r++) {
System.out.print(sections[r] + "\t");
for (int c = 0; c < prices[r].length; c++) {
System.out.print("$" + prices[r][c] + "\t");
}
System.out.println();
}
}
}
public class AccessElement {
public static void main(String[] args) {
// Ticket prices by section (rows) and day (columns)
// Rows: 0=Front, 1=Middle, 2=Back
// Cols: 0=Mon, 1=Tue, 2=Wed, 3=Thu, 4=Fri
int[][] prices = {
{50, 50, 55, 55, 75}, // Front row
{40, 40, 45, 45, 60}, // Middle row
{25, 25, 30, 30, 45} // Back row
};
// Customer wants: middle section, Friday
int wantRow = ;
int wantCol = ;
int price = prices[wantRow][wantCol];
String[] sections = {"Front", "Middle", "Back"};
String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
System.out.println("=== Ticket Lookup ===");
System.out.println("Section: " + sections[wantRow]);
System.out.println("Day: " + days[wantCol]);
System.out.println("Price: $" + price);
// Show full price chart
System.out.println("\n=== Full Price Chart ===");
System.out.print(" ");
for (String day : days) {
System.out.print(day.substring(0, 3) + "\t");
}
System.out.println();
for (int r = 0; r < prices.length; r++) {
System.out.print(sections[r] + "\t");
for (int c = 0; c < prices[r].length; c++) {
System.out.print("$" + prices[r][c] + "\t");
}
System.out.println();
}
}
}
Access with two indices: grid[1][2] means row 1, column 2.
Mark a seat as reserved
Update a value at a specific position.
public class UpdateCell {
public static void main(String[] args) {
// Seating chart: 0 = available, 1 = reserved
int[][] seats = {
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
// Customer reservations (row, col)
int reserveRow = ;
int reserveCol = ;
System.out.println("=== Before Reservation ===");
printSeating(seats);
// Make the reservation
seats[reserveRow][reserveCol] = 1;
System.out.println("\n=== After Reserving Row " +
(reserveRow + 1) + ", Seat " + (reserveCol + 1) + " ===");
printSeating(seats);
// Reserve more seats
seats[0][0] = 1;
seats[2][3] = 1;
System.out.println("\n=== After Additional Reservations ===");
printSeating(seats);
// Count available seats
int available = 0;
for (int[] row : seats) {
for (int seat : row) {
if (seat == 0) available++;
}
}
System.out.println("\nAvailable seats: " + available);
}
static void printSeating(int[][] seats) {
System.out.println(" 1 2 3 4");
for (int r = 0; r < seats.length; r++) {
System.out.print((r + 1) + " ");
for (int c = 0; c < seats[r].length; c++) {
System.out.print(seats[r][c] == 0 ? "O " : "X ");
}
System.out.println();
}
}
}
public class UpdateCell {
public static void main(String[] args) {
// Seating chart: 0 = available, 1 = reserved
int[][] seats = {
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
// Customer reservations (row, col)
int reserveRow = ;
int reserveCol = ;
System.out.println("=== Before Reservation ===");
printSeating(seats);
// Make the reservation
seats[reserveRow][reserveCol] = 1;
System.out.println("\n=== After Reserving Row " +
(reserveRow + 1) + ", Seat " + (reserveCol + 1) + " ===");
printSeating(seats);
// Reserve more seats
seats[0][0] = 1;
seats[2][3] = 1;
System.out.println("\n=== After Additional Reservations ===");
printSeating(seats);
// Count available seats
int available = 0;
for (int[] row : seats) {
for (int seat : row) {
if (seat == 0) available++;
}
}
System.out.println("\nAvailable seats: " + available);
}
static void printSeating(int[][] seats) {
System.out.println(" 1 2 3 4");
for (int r = 0; r < seats.length; r++) {
System.out.print((r + 1) + " ");
for (int c = 0; c < seats[r].length; c++) {
System.out.print(seats[r][c] == 0 ? "O " : "X ");
}
System.out.println();
}
}
}
public class UpdateCell {
public static void main(String[] args) {
// Seating chart: 0 = available, 1 = reserved
int[][] seats = {
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
// Customer reservations (row, col)
int reserveRow = ;
int reserveCol = ;
System.out.println("=== Before Reservation ===");
printSeating(seats);
// Make the reservation
seats[reserveRow][reserveCol] = 1;
System.out.println("\n=== After Reserving Row " +
(reserveRow + 1) + ", Seat " + (reserveCol + 1) + " ===");
printSeating(seats);
// Reserve more seats
seats[0][0] = 1;
seats[2][3] = 1;
System.out.println("\n=== After Additional Reservations ===");
printSeating(seats);
// Count available seats
int available = 0;
for (int[] row : seats) {
for (int seat : row) {
if (seat == 0) available++;
}
}
System.out.println("\nAvailable seats: " + available);
}
static void printSeating(int[][] seats) {
System.out.println(" 1 2 3 4");
for (int r = 0; r < seats.length; r++) {
System.out.print((r + 1) + " ");
for (int c = 0; c < seats[r].length; c++) {
System.out.print(seats[r][c] == 0 ? "O " : "X ");
}
System.out.println();
}
}
}
public class UpdateCell {
public static void main(String[] args) {
// Seating chart: 0 = available, 1 = reserved
int[][] seats = {
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
};
// Customer reservations (row, col)
int reserveRow = ;
int reserveCol = ;
System.out.println("=== Before Reservation ===");
printSeating(seats);
// Make the reservation
seats[reserveRow][reserveCol] = 1;
System.out.println("\n=== After Reserving Row " +
(reserveRow + 1) + ", Seat " + (reserveCol + 1) + " ===");
printSeating(seats);
// Reserve more seats
seats[0][0] = 1;
seats[2][3] = 1;
System.out.println("\n=== After Additional Reservations ===");
printSeating(seats);
// Count available seats
int available = 0;
for (int[] row : seats) {
for (int seat : row) {
if (seat == 0) available++;
}
}
System.out.println("\nAvailable seats: " + available);
}
static void printSeating(int[][] seats) {
System.out.println(" 1 2 3 4");
for (int r = 0; r < seats.length; r++) {
System.out.print((r + 1) + " ");
for (int c = 0; c < seats[r].length; c++) {
System.out.print(seats[r][c] == 0 ? "O " : "X ");
}
System.out.println();
}
}
}
Assign directly: grid[row][col] = value. Arrays are mutable.
Sum all values
Calculate a total by traversing every cell.
public class SumAll {
public static void main(String[] args) {
// Monthly sales by product (in units)
// Rows: Products (0=Widgets, 1=Gadgets, 2=Gizmos)
// Cols: Months (0=Jan, 1=Feb, 2=Mar)
int[][] sales = {
{120, 135, 150}, // Widgets
{80, 95, 110}, // Gadgets
{200, 180, 220} // Gizmos
};
// Quarterly sales (4 products, 4 quarters)
int[][] quarterly = {
{1200, 1350, 1500, 1400},
{800, 950, 1100, 1050},
{2000, 1800, 2200, 2100},
{500, 600, 700, 650}
};
int[][] data = ;
// Calculate total sales
int grandTotal = 0;
for (int row = 0; row < data.length; row++) {
for (int col = 0; col < data[row].length; col++) {
grandTotal += data[row][col];
}
}
System.out.println("=== Sales Summary ===");
System.out.println("Grand Total: " + grandTotal + " units");
// Calculate row totals (per product)
System.out.println("\n=== Per Product ===");
String[] products = {"Widgets", "Gadgets", "Gizmos", "Sprockets"};
for (int row = 0; row < data.length; row++) {
int rowTotal = 0;
for (int col = 0; col < data[row].length; col++) {
rowTotal += data[row][col];
}
System.out.println(products[row] + ": " + rowTotal);
}
// Calculate column totals (per month/quarter)
System.out.println("\n=== Per Period ===");
for (int col = 0; col < data[0].length; col++) {
int colTotal = 0;
for (int row = 0; row < data.length; row++) {
colTotal += data[row][col];
}
System.out.println("Period " + (col + 1) + ": " + colTotal);
}
}
}
public class SumAll {
public static void main(String[] args) {
// Monthly sales by product (in units)
// Rows: Products (0=Widgets, 1=Gadgets, 2=Gizmos)
// Cols: Months (0=Jan, 1=Feb, 2=Mar)
int[][] sales = {
{120, 135, 150}, // Widgets
{80, 95, 110}, // Gadgets
{200, 180, 220} // Gizmos
};
// Quarterly sales (4 products, 4 quarters)
int[][] quarterly = {
{1200, 1350, 1500, 1400},
{800, 950, 1100, 1050},
{2000, 1800, 2200, 2100},
{500, 600, 700, 650}
};
int[][] data = ;
// Calculate total sales
int grandTotal = 0;
for (int row = 0; row < data.length; row++) {
for (int col = 0; col < data[row].length; col++) {
grandTotal += data[row][col];
}
}
System.out.println("=== Sales Summary ===");
System.out.println("Grand Total: " + grandTotal + " units");
// Calculate row totals (per product)
System.out.println("\n=== Per Product ===");
String[] products = {"Widgets", "Gadgets", "Gizmos", "Sprockets"};
for (int row = 0; row < data.length; row++) {
int rowTotal = 0;
for (int col = 0; col < data[row].length; col++) {
rowTotal += data[row][col];
}
System.out.println(products[row] + ": " + rowTotal);
}
// Calculate column totals (per month/quarter)
System.out.println("\n=== Per Period ===");
for (int col = 0; col < data[0].length; col++) {
int colTotal = 0;
for (int row = 0; row < data.length; row++) {
colTotal += data[row][col];
}
System.out.println("Period " + (col + 1) + ": " + colTotal);
}
}
}
Use nested loops: outer loop for rows, inner loop for columns.
Find a value's position
Search for a value and return its row/column.
public class FindPosition {
public static void main(String[] args) {
// Movie theater seat map with seat IDs
String[][] seatMap = {
{"A1", "A2", "A3", "A4", "A5"},
{"B1", "B2", "B3", "B4", "B5"},
{"C1", "C2", "C3", "C4", "C5"},
{"D1", "D2", "D3", "D4", "D5"}
};
// Find this seat
String targetSeat = ;
// Search for the seat
int foundRow = -1;
int foundCol = -1;
for (int row = 0; row < seatMap.length; row++) {
for (int col = 0; col < seatMap[row].length; col++) {
if (seatMap[row][col].equals(targetSeat)) {
foundRow = row;
foundCol = col;
break; // Found it, exit inner loop
}
}
if (foundRow != -1) break; // Exit outer loop too
}
System.out.println("=== Seat Finder ===");
System.out.println("Looking for seat: " + targetSeat);
if (foundRow != -1) {
System.out.println("Found at position:");
System.out.println(" Row index: " + foundRow + " (Row " + (foundRow + 1) + ")");
System.out.println(" Col index: " + foundCol + " (Seat " + (foundCol + 1) + ")");
// Calculate walking directions
System.out.println("\nDirections: Walk to row " + (foundRow + 1) +
", then count " + (foundCol + 1) + " seat(s) from the left.");
} else {
System.out.println("Seat not found!");
}
// Show the map with target highlighted
System.out.println("\n=== Seat Map ===");
for (int row = 0; row < seatMap.length; row++) {
for (int col = 0; col < seatMap[row].length; col++) {
if (row == foundRow && col == foundCol) {
System.out.print("[" + seatMap[row][col] + "]\t");
} else {
System.out.print(" " + seatMap[row][col] + " \t");
}
}
System.out.println();
}
}
}
public class FindPosition {
public static void main(String[] args) {
// Movie theater seat map with seat IDs
String[][] seatMap = {
{"A1", "A2", "A3", "A4", "A5"},
{"B1", "B2", "B3", "B4", "B5"},
{"C1", "C2", "C3", "C4", "C5"},
{"D1", "D2", "D3", "D4", "D5"}
};
// Find this seat
String targetSeat = ;
// Search for the seat
int foundRow = -1;
int foundCol = -1;
for (int row = 0; row < seatMap.length; row++) {
for (int col = 0; col < seatMap[row].length; col++) {
if (seatMap[row][col].equals(targetSeat)) {
foundRow = row;
foundCol = col;
break; // Found it, exit inner loop
}
}
if (foundRow != -1) break; // Exit outer loop too
}
System.out.println("=== Seat Finder ===");
System.out.println("Looking for seat: " + targetSeat);
if (foundRow != -1) {
System.out.println("Found at position:");
System.out.println(" Row index: " + foundRow + " (Row " + (foundRow + 1) + ")");
System.out.println(" Col index: " + foundCol + " (Seat " + (foundCol + 1) + ")");
// Calculate walking directions
System.out.println("\nDirections: Walk to row " + (foundRow + 1) +
", then count " + (foundCol + 1) + " seat(s) from the left.");
} else {
System.out.println("Seat not found!");
}
// Show the map with target highlighted
System.out.println("\n=== Seat Map ===");
for (int row = 0; row < seatMap.length; row++) {
for (int col = 0; col < seatMap[row].length; col++) {
if (row == foundRow && col == foundCol) {
System.out.print("[" + seatMap[row][col] + "]\t");
} else {
System.out.print(" " + seatMap[row][col] + " \t");
}
}
System.out.println();
}
}
}
Return early when found. Return special value (-1, -1) if not found.
Exercise: JaggedArray.java
Explore jagged arrays where rows have different lengths