11: 2D array == pow(fun, 2)

AP Computer Science A Dec 13, 2023

Dive into the Wild World of 2D Arrays: The KISJ Edition

Hey there, KISJ coders! Are you ready to dive into the matrix? I mean, the world of 2D arrays in Java? Trust me, it's as thrilling as trying to sneak to the deli without a teacher, and this is the last concept to learn before the long good winter break.

What's a 2D Array? A Maze of Numbers!

Picture this: A 2D array is like having a stack of bento boxes, each box filled with delicious numbers instead of sushi! 🍱

Declaring a 2D Array in Java

Declaring a 2D array in Java is easier than convincing STUCO members to smile during assembly. 😅 Here's how you do it:

int[][] coolArray = new int[3][6];

This line is like saying, "Hey Java, give me a 3×6 grid of numbers!" It is similar to how we declare a 1D array, but with extra "[]" to tell we are making a 2D array.

Initializing a 2D Array

Now, let's fill this array like we're cramming knowledge before a pop quiz (or a 🎁). It's like setting up your own little number buffet.

int[][] coolArray = {
	{1, 2, 3},
	{4, 5, 6}
};

Accessing Data in a 2D Array

Accessing data in a 2D array is like finding a teacher that you have never heard of in school. In that case, you will email them to know about what floor and what room they are in. Similarly, in a 2D array, we need to give two indexes—the first one for selecting the array within the array we want to search, and the second one to find the element in the second array.

coolArray[0][2]

This is like saying, "In the first row, give me the third number." Sneaky, right?

Looping Through a 2D Array

Looping through a 2D array is like the endless loop of reassessment requirements if you don't do your homework. (no assignments == no reassessment 😲) Here's how you loop:

int coolSum = 0;
for (int i = 0; i < coolArray.length; i++) {
	for (int j = 0; j < coolArray[i].length; j++) {
		coolSum += coolArray[i][j];
	}
}

Since we need two indexes, we need to use two for loops to loop through all the elements in the 2D array.


So there you have it! 2D arrays in Java are not so different from 1D array. They might seem complicated at first, like figuring out the new grading policy, but once you get the hang of it, it's a piece of cake (or a piece of kimchi if you prefer).

Keep coding, and maybe one day you'll write an AI to automate STUCO presentations—with genuine smiles! 😄👩‍💻👨‍💻

Tags