Learn Java Easy. Chapter 8. Bud’s Job. 2D Arrays

Exercises Topic 8 – Bud’s Work. 2D Arrays

Chapter 8. Bud’s Work. 2D Arrays

The days feel endless. I am eagerly waiting for Rich’s visit, but he is taking longer than usual. It has 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; recently he introduced me to his friend Pedro. He also helps the prison officers with the security software. He is a very introverted person. He barely talks to anyone and usually spends most of the day on the computer. I think, with 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 chatting with anyone, but still, having an activity that keeps you busy is the best thing that can happen to you while you’re locked up here.

If I want to be his new apprentice, I must know exactly what they do. At this moment, I have no idea. Bud thinks I am ready to perform small tasks and that, little by little, he will give me more responsibilities.

Without prior notice, I am informed that I have a visitor. I hope it is Rich, but it is not. Again, it is 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 easiest way would be to fake some kind of ailment, like a dental problem, so they transfer me to an external doctor.

The problem would be to fool the police officers who are supposed to escort me there. If I managed that, I suppose the next step of the plan would be to meet with Rich and try to get a confession out of him.

Importance of Two-Dimensional Arrays in Java

Two-dimensional arrays in Java allow us to represent data in a table format, distributed in rows and columns. Also known as 2D arrays, these arrays can be considered an evolution of the arrays we saw in the previous topic. Arrays work only in one dimension. Arrays allow storing information in table form. This arrangement makes them useful in many applications.

By using 2D arrays, it is 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 and graphics creation 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[][] myArray;

After declaring the array, 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:

arrayName = new dataType[numRows][numColumns];

For example, to create an integer array with 3 rows and 4 columns:

myArray = new int[3][4];

Just like with arrays, I started explaining step by step how to declare it, then create it, and finally assign values. I think this is the most visual way to understand how Java syntax works. Although, in practice, the easiest way is to do everything at once in a single line. We save code and everything looks much tidier. Let’s see how it’s done.

Declaration, Creation, and Value Assignment in One Line

int[][] myArray = new int[3][4];

I think the example explains itself. In the first part of the line, before the equal sign, we declare the array and name it as we like. After the equal sign, we create the array using new plus the data type and, inside brackets, assign the number of rows and columns we need.

Accessing Elements of a 2D Array

To access a specific element in a 2D array, you must use two indices: one for the row and one for the column. The basic syntax is:

arrayName[row][column]

Imagine you have an array called “myArray” of size 3×3 and you want to access the element in the second row and third column, you would probably do it like this:

int value = myArray[2][3];

But you are 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 do it like this:

int value = myArray[1][2];

We can see it with another example, given the following array:

int[][] myArray = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

int value = myArray[1][1]; // 5

If we want to change the value 6 to 14, we would do it as follows:

myArray[1][2] = 14;

Initialization of 2D Arrays

– You can initialize an array directly when you declare it, specifying all its elements beforehand:

int[][] myArray = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

– You can also declare an array first and assign values to its elements later:

int[][] myArray = new int[3][3]; myArray[0][0] = 1;

myArray[0][1] = 2;

myArray[0][2] = 3;

myArray[1][0] = 4;

myArray[1][1] = 5;

myArray[1][2] = 6;

myArray[2][0] = 7;

myArray[2][1] = 8;

myArray[2][2] = 9;

Traversing 2D Arrays Using Loops

To traverse arrays we used a loop. In this case, one will not be enough since we have elements placed in rows and columns. Therefore, we will have to use two nested loops.

This would be the structure we would follow:

for (int i = 0; i < myArray.length; i++) { // Traverse rows

    for (int j = 0; j < myArray[i].length; j++) { // Traverse columns

        System.out.println("Element at [" + i + "][" + j + "]: " + myArray[i][j]);

    }

}

If we start analyzing the code, in the first line we find myArray.length. That is basically the number of rows our array has. We can leave it written like that or simply write the number of rows.

In the next line, we find the second loop. Usually, 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 of our array, traverse each column.

The last line simply serves to print the data on the screen and make sure the loop is being traversed correctly and that we have done everything right.

Sum of Elements in an Array

Now that we know how to traverse arrays, let’s do a couple of very basic operations we can perform thanks to loops. The first one is the sum of the elements. The structure is as follows:

int sum = 0;

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

System.out.println("The sum of all elements is: " + sum);

Searching for Specific Elements

int[][] myArray = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

int search = 5;
boolean found = false;

for (int i = 0; i < myArray.length; i++) {
    for (int j = 0; j < myArray[i].length; j++) {
        if (myArray[i][j] == search) {
            System.out.println("Element " + search + " found at [" + i + "][" + j + "]");
            found = true;
            break;
        }
    }
    if (found) break;
}

if (!found) {
    System.out.println("Element " + search + " not found.");
}

It is worth noting that when dealing with boolean variables and working in an if, to write the conditional we can do it as follows:

If (found == true) {

}

Although, the most correct way is to do it like this:

If (found) {

}

The same happens if it is false, we can do it like this:

If (found == false) {

}

But it is recommended to do it like this:

if (!found) {

}

This is due to three reasons:

  • Clarity and Readability: It is clearer and more concise to write if (boolean) than if (boolean == true).
  • Avoid Common Errors: Using if (boolean == true) introduces the possibility of typographical errors, such as accidentally writing if (boolean = true).
  • Programming Convention: In Java and many other programming languages, it is a convention and good practice to simply use the boolean variable in a control structure, rather than explicitly comparing it to true.

Summary of What Was Learned

Two-dimensional arrays or 2D arrays are structures capable of organizing data in tables composed of rows and columns. This form of storage is especially useful for programmers in many scenarios. This is because they allow managing information in an orderly and logical way. In a two-dimensional array, elements can be accessed easily using two indices: one for rows and one for columns.

Many search and sorting algorithms use 2D arrays, since thanks to them it is possible to work with data sets structured in two dimensions. For example, they can be used to represent game boards, graphics, and even simple databases, where ease of access and data manipulation is essential.

But it doesn’t end there; two-dimensional arrays are characterized by their flexibility and ease of implementation, which makes them suitable for a wide range of applications. So, in summary, 2D arrays are a powerful and versatile tool that, in some cases, simplifies programming and provides solutions for complex problems.

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏