Chapter 8. Bud’s Job. 2D Arrays
The days feel endless. I’m anxiously waiting for Rich’s visit, but it’s taking longer than usual. It’s been ten days since I had the conversation with Chani’s cousin, and he still hasn’t come to see me. Bud keeps me entertained; he recently introduced me to his friend Pedro. He also helps the prison staff with security software. He’s a very introverted person. He hardly talks to anyone and usually spends most of the day on the computer. I think, given his personality, it’s lucky for him that they let him spend so much time glued to the computer.
On the other hand, Bud is more sociable. He enjoys talking with anyone, but even so, having an activity that keeps you busy is the best thing that can happen to you while you’re locked up in here.
If I want to be his new apprentice, I need to know exactly what they do. Right now, I have no idea. Bud thinks I’m ready to perform small tasks and that, little by little, he’ll give me more responsibilities.

Without warning, I’m informed that I have a visitor. I hope it’s Rich, but it’s not. Again, it’s Chani’s cousin. This time he tells me they have a plan to prove my innocence. They want to set a trap for Rich. The problem is that, to carry it out, I need to be outside the prison. The simplest way would be to fake some kind of ailment, like a dental problem, so they would transfer me to an external doctor.
The problem would be evading the police officers who would supposedly escort me there. If I managed to do that, I suppose the next step of the plan would be to meet with Rich and try to get a confession out of him.

I’m not at all sure about this. If I leave and escape from the officers escorting me, I’ll get into really big trouble. They would convict me of another crime, and besides, they wouldn’t let me participate in any activities inside the prison. I would have to forget about helping Bud and Pedro with the security system. But, on the other hand, if I do nothing, I’ll most likely have to spend a long time here.
I think it’s crazy, but if I have to get out of prison, I need to ask advice from someone who has lived here for several years. So I think the best option is to talk to Bud about it. Maybe he has ideas on how to get out for a few hours without getting into trouble.
I thought he would tell me I was crazy and to forget about the idea. But far from it, he said he could help me. However, first he wants me to understand what his job in prison is. For this, he says I have to learn about 2D arrays. He’s going to explain how they work and then give me 10 examples. If I can manage to handle them, he’ll help me get out of prison.
Importance of Two-Dimensional Arrays in Java
Two-dimensional arrays in Java allow us to represent data in table format, distributed in rows and columns. Also known as 2D arrays, these matrices can be considered an evolution of the arrays we saw in the previous topic. Arrays work in only one dimension. Matrices allow storing information in table form. This arrangement makes them useful in many applications.
When using 2D arrays, it’s possible to structure data in a more organized way. Additionally, they facilitate access to elements through indices, which speeds up tasks such as data manipulation and searching.
Two-dimensional arrays are also essential for implementing algorithms that require a table structure, such as some search and sorting algorithms. Thanks to their versatility, they are used in various fields, from video game creation and graphics to scientific simulations and data analysis.
Declaration and Creation of 2D Arrays
To declare a 2D array, you must specify the data type it will store and its name. Basically like this:
int[][] myMatrix;
After declaring the matrix, you need to create it, that is, allocate memory for it. For this, you must specify how many rows and columns it will have. The syntax is:
matrixName = new dataType[numRows][numColumns];
For example, to create an integer matrix with 3 rows and 4 columns:
myMatrix = new int[3][4];
Just like with arrays, I’ve started by explaining step by step how to declare, then create, and finally assign values. I think this is the most graphic way to understand how Java syntax works. Although, in practice, the simplest thing is to do everything at once in a single line. We save code and everything becomes much more organized. Let’s see how it’s done.
Declaration, Creation, and Value Assignment in a Single Line
int[][] myMatrix = new int[3][4];
I think the example explains itself. In the first part of the line, before the equal sign, we declare the matrix and name it as we see fit. After the equal sign, we create the matrix using new plus the data type and, in brackets, we assign the number of rows and columns we need.
Accessing Elements of a 2D Matrix
To access a specific element in a 2D matrix, you must use two indices: one for the row and another for the column. The basic syntax is:
matrixName[row][column]
Imagine you have a matrix called “myMatrix” of size 3×3 and you want to access the element in the second row and third column. You might think to do it like this:
int value = myMatrix[2][3];
But you’d be wrong. Remember that, just like with arrays, we don’t start from 1, but from 0. Therefore, to access the value in the second row and third column, we would do it like this:
int value = myMatrix[1][2];
We can see it with another example, given the following matrix:
int[][] myMatrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int value = myMatrix[1][1]; // 5
If we want to change the value 6 to 14, we would do it as follows:
myMatrix[1][2] = 14;
Initialization of 2D Matrices
- You can initialize a matrix directly when you declare it, specifying all its elements in advance:
int[][] myMatrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
- You can also declare a matrix first and assign values to its elements afterwards:
int[][] myMatrix = new int[3][3];
myMatrix[0][0] = 1;
myMatrix[0][1] = 2;
myMatrix[0][2] = 3;
myMatrix[1][0] = 4;
myMatrix[1][1] = 5;
myMatrix[1][2] = 6;
myMatrix[2][0] = 7;
myMatrix[2][1] = 8;
myMatrix[2][2] = 9;
Traversing 2D Matrices Using Loops
To traverse arrays, we used one loop. In this case, one won’t be enough since we have elements arranged in rows and columns. Therefore, we’ll need to use two nested loops.
This would be the structure we would follow:
for (int i = 0; i < myMatrix.length; i++) { // Traverses the rows
for (int j = 0; j < myMatrix[i].length; j++) { // Traverses the columns
System.out.println("Element at [" + i + "][" + j + "]: " + myMatrix[i][j]);
}
}
If we start analyzing the code, in the first line we find myMatrix.length. That’s basically the number of rows our matrix has. We can leave it written like that or simply write the number of rows.
In the next line, we find the second loop. Generally, when we create a for loop, we call the variable “i”; for a second loop, the letter “j” is used. Basically, what it does is, for each row in our matrix, traverse each column.
The last line simply serves to print the data on the screen and ensure that the loop is being traversed correctly and that we’ve done everything right.
Sum of Elements in a Matrix
Now that we know how to traverse matrices, let’s look at a couple of very basic operations we can perform using loops. The first one is the sum of elements. The structure is as follows:
int sum = 0;
for (int i = 0; i < myMatrix.length; i++) {
for (int j = 0; j < myMatrix[i].length; j++) {
sum += myMatrix[i][j];
}
}
System.out.println("The sum of all elements is: " + sum);
Searching for Specific Elements
int[][] myMatrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int searchFor = 5;
boolean found = false;
for (int i = 0; i < myMatrix.length; i++) {
for (int j = 0; j < myMatrix[i].length; j++) {
if (myMatrix[i][j] == searchFor) {
System.out.println("Element " + searchFor + " found at [" + i + "][" + j + "]");
found = true;
break;
}
}
if (found) break;
}
if (!found) {
System.out.println("Element " + searchFor + " not found.");
}
In the first part of this code, we find the same matrix we were using in previous exercises. It’s a matrix that’s declared and has values already assigned. After that, we have two variables. The first is an int type and is the element we want to find. The second is a boolean type, by default it will be false, but when the program finds the element, we need to make it change to true. We could perfectly write our program without using this last variable, but there isn’t always such a good opportunity to use a boolean in our examples.
Up to here, nothing we didn’t know. Now we traverse the loop using nesting, just as we did in the previous examples. If you notice, it’s exactly the same code and the same structure. The only thing that changes is that we’ve added an if, and as you can see, its operation is very simple. If it finds the element we’re looking for, it will tell us exactly what position it’s in and will close the loop thanks to the break we added. If it doesn’t find it, it will continue searching
We use the boolean found to make the program end completely if we’ve already found the desired element or to display a final message saying that the element could not be found.
It’s worth noting that when dealing with boolean variables and working with an if, we can write the conditional in the following way:
if (found == true) {
}
Although, the more correct way to do it is:
if (found) {
}
The same applies if it’s false, we can do it this way:
if (found == false) {
}
But it’s recommended to do it like this:
if (!found) {
}
This is due to three reasons:
- Clarity and Readability:
It’s clearer and more concise to write if (boolean) than if (boolean == true).
The expression if (boolean) is easier to read and understand because it’s directly verifying the boolean condition.
- Avoiding Common Errors:
Using if (boolean == true) introduces the possibility of typographical errors, such as accidentally writing if (boolean = true).
If we write the equal sign with a single equals, it will cause serious errors in the program and it won’t function correctly. Often, detecting this error is quite difficult, so it’s better to avoid the possibility of it happening.
- Programming Convention:
In Java and many other programming languages, it’s a convention and good practice to simply use the boolean variable in a control structure, rather than explicitly comparing it with true.
Summary of What We’ve Learned
Two-dimensional matrices or 2D arrays are structures capable of organizing data in tables composed of rows and columns. This form of storage is particularly useful for programmers in numerous scenarios. This is because they allow information to be managed in an orderly and logical manner. In a two-dimensional matrix, elements can be easily accessed using two indices: one for rows and another for columns.
Many search and sorting algorithms use 2D arrays, as they allow working with data sets structured in two dimensions. For example, they can be used to represent game boards, graphs, and even simple databases, where ease of access and manipulation of data is essential.
But it doesn’t stop there; two-dimensional matrices are characterized by their flexibility and ease of implementation, which makes them ideal for a wide range of applications. So, in summary, 2D arrays constitute a powerful and versatile tool that, in some cases, simplifies programming and provides solutions for complex problems.