Learn Java Easy. Chapter 7. Rich’s Cousin’s Visit. Random Arrays

Chapter 7. Rich’s Cousin’s Visit. Random Arrays

Today I received an unexpected visit. I’m still a bit dazed. Around 12 noon, a guard came to get me and took me to the visiting room. I thought it would be my mother or perhaps the lawyer, but it was Chani’s cousin. I had never seen him before, so I didn’t know it was him until he introduced himself.

I remained silent for several seconds. I could feel myself getting angry little by little, until I started cursing and stumbling over my words, as I wanted to express many things at the same time. At one point, one of the guards came over and asked me to calm down. The truth is, it was a good release. After that, I felt much calmer and willing to hear what he had to say.

 

Besides being angry, I was very curious. All the answers I had been yearning for during weeks were right in front of me. I wanted to know exactly what kind of trouble Chani was involved in, why he had done it, and above all, why he had implicated me. Perhaps it had all been a mistake. Maybe he was remorseful and wanted to exonerate me. Countless questions were running through my head, and I didn’t know which one to ask first.

 

I was just about to say something when he interrupted me. He told me he knew what I was thinking, that he knew I believed Chani was guilty, but that wasn’t the case. Although all the evidence pointed to him, he was actually innocent.

 

It seemed pretty hard to believe, so I asked him how he could be so sure. Then he told me that Chani had sent him to tell me the true story. I became furious again. I told him that if he knew where Chani was, he should tell or he would be guilty of harboring a fugitive. Once again, the guard came to call me out.

 

Once I calmed down, the cousin proceeded to tell me the story. According to him, Chani had nothing to do with it. He had no choice but to flee when he discovered the real culprits’ plan: Rich and Fernando.

 

 

It appears that the day before the party, Chani arrived home and went straight to his room. Fernando and Rich were in the living room and didn’t notice his presence. Without fear of being discovered, they began to discuss their plan. At that moment, they were obtaining the illegal software they would later use to extort companies.

 

Chani received a call and was discovered. The three of them sat down in the living room, and it was then that he realized they were using my computer. Finding themselves cornered, they had no choice but to offer him a part in the crime. They explained the plan in detail, including the part where, if something went wrong, they would blame me.

 

Despite their insistence, Chani refused. That’s when they threatened him. They came up with a way to incriminate him if he didn’t cooperate. They advised him to think about it for a few hours and said they wanted a definitive answer the next day.

 

During the night, they got that answer. But it wasn’t what they expected. So, things became even more tense, and they physically threatened him. They forced him to leave as soon as possible and also coerced him into not saying anything.

 

The story made sense, but I didn’t believe it. Rich is my friend. He would never do something like that to me. After a few seconds of silence, he looked at me intently and asked if I believed him. I told him I didn’t, and then he pulled out his phone. He showed me an audio recording from the night of the party in which Rich could be heard telling him to leave that same night and never come back.

 

Chani tried to find evidence against them, but there was a lot of noise at the party, and Rich is very astute. From that conversation, only the part where he tells him to leave the city that very night can be distinguished.

 

It seems Chani has a plan to unmask Rich, but he might need my help. I don’t know how I can help while locked up in here. Maybe during one of his visits, I could get a confession or at least some information. The worst part about being in isolation isn’t just the lack of information, but also that I’m not very useful. After the brief conversation, I returned to my cell. I’m still processing the information. Rich has come to visit me several times and has always seemed very concerned. I didn’t expect this, but it makes sense. Now I just hope he comes to see me again, so I can clear things up face to face.

 

To try to think about something else, I’ve asked Bud to continue with the Java lessons. He seems especially motivated. He told me that once I learn about arrays, he’ll be able to explain exactly how he helps the prison staff with the jail’s software. For now, I don’t want to tell him anything about my personal situation. I know it would worry him. So, for the time being, I put on a brave face and try to learn something.

Arrays

 

In Java, arrays are a basic way to store multiple values of the same type in a single variable. Unlike normal variables that can only contain one value, an array can store multiple values, called elements, which are organized in a specific order and accessed using numbers called indices.

 

An array is created by specifying what type of data it will hold and how many elements it will store. For example, an int array of integers with a size of 5 can store five whole numbers. Arrays in Java start counting from 0, so the first element is at position 0.

 

 

Importance of Arrays in Programming

 

  • They allow data to be organized in a structured manner, facilitating access and manipulation.
  • With arrays, we can efficiently store large amounts of related data and access them through indices, instead of managing many independent variables.
  • Array elements can be quickly accessed using their index, which is crucial for applications that need fast and frequent data reading or modification operations.
  • Furthermore, arrays allow common operations such as iteration, searching, sorting, and data manipulation to be performed easily. Many algorithms and data structures are based on arrays due to their simplicity and efficiency, such as sorting and searching algorithms.
  • In real-world applications, arrays are widely used, from game development to data processing and scientific applications, where they are essential for managing large datasets and performing complex numerical calculations.

 

 

Array Declaration

 

The declaration of an array in Java is done by specifying the data type of the elements it will contain, followed by square brackets [] and the array name.

 

Step 1: Declaring the array

 

type[] arrayName;

 

Example:

 

int[] numbers; // Declaration of an integer array
String[] names; // Declaration of a string array
double[] temperatures; // Declaration of a double array

 

Step 2: Creating the array

 

arrayName = new type[size];

 

Example:

 

numbers = new int[5]; // Creates an integer array with 5 elements
names = new String[3]; // Creates a string array with 3 elements
temperatures = new double[7]; // Creates a double array with 7 elements

 

However, you’ll rarely use this structure. It’s much simpler, faster, and more effective if we do it all in one line. Besides, it will be much easier for you to remember.

 

 

Declaration and Creation in a Single Line

 

type[] arrayName = new type[size];

 

Examples:

 

int[] numbers = new int[5]; // Declaration and creation of an integer array with 5 elements
String[] names = new String[3]; // Declaration and creation of a string array with 3 elements
double[] temperatures = new double[7]; // Declaration and creation of a double array with 7 elements

 

 

Assigning Values to Arrays

 

int[] numbers = new int[5];

numbers[0] = 10;

        numbers[1] = 20;

        numbers[2] = 30;

        numbers[3] = 40;

        numbers[4] = 50;

       

 

Now each element in our array has a value. For example, if we want to display the fifth position on the screen, we’ll do it in the following way:

 

        System.out.println(numbers[4]);

 

String[] names = new String[3];

        names[0] = "Lucía";

        names[1] = "Pedro";

        names[2] = "Luís";

       

 

No further theoretical explanation is necessary. This topic is quite simple to understand just by looking at the exercises. At least for now. I’ve only shown examples of natural numbers (int type variables) and text (String type variables). But it’s clear that, for example, we can use decimal numbers if we use a double or characters with a char. For the latter, instead of using double quotes ” “, we would use single quotes ‘ ‘.

 

Regardless of the variable type, the same structure is always followed.

 

 

Assigning Values to Arrays in a Single Line

 

Sometimes you’ll encounter brackets in arrays. They are also used to assign values. This is the structure used for this purpose:

 

  • type[] arrayName = {value1, value2, value3, …};

 

Of course, let’s see it with an example. We’ll start with an int array with 5 elements. We’ll assign values and display the fifth element. Remember that arrays always start at position 0. So our fifth element is at position 4.

 

       

        int[] numbers = {10, 20, 30, 40, 50};

        System.out.println(numbers[4]);

 

Now let’s continue with our text example. We have three names and we’ll declare and assign values to an array in a single line.

 

  • String[] names = {“Lucía”, “Pedro”, “Luis”};

 

As you can see, at first glance, this way of creating arrays and assigning values is much simpler. The code looks more organized and elegant. However, it’s not all advantages. Not having the position of each element indicated can sometimes make us get lost or a bit confused. As I mentioned before, the array always starts at position zero and goes up to the maximum number of elements we have. Having the position next to each value is very convenient, and with a quick glance, we can visualize the entire structure of our array in our head.

 

 

Traversing Arrays Using Loops in Java

 

Traversing an array means accessing each of its elements one by one. Loops are essential tools for this task, as they allow us to iterate over array elements in a simple and efficient way. The simplest way to do this task is to use a for loop.

 

 

Example: Traversing an Integer Array using a For Loop

 

public class Main {

    public static void main(String[] args) {

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

        // We know the array size is 5

        for (int i = 0; i < 5; i++) {

            System.out.println(numbers[i]);

        }

    }

}

 

 

Example: Traversing a String Array

 

public class Main {

    public static void main(String[] args) {

        String[] colors = {"Red", "Green", "Blue", "Yellow"};

        // We know the array size is 4

        for (int i = 0; i < 4; i++) {

            System.out.println(colors[i]);

        }

    }

}

 

 

Example: Traversing a Character Array (char)

 

public class Main {

   public static void main(String[] args) {

        char[] letters = {'A', 'B', 'C'};

        // We know the array size is 3

        for (int i = 0; i < 3; i++) {

            System.out.println(letters[i]);

        }

    }

}

   

       

 

Notice that in all examples, the loop’s first position is 0 since arrays always start from 0.

Summary of What We’ve Learned

 

In Java, an array is a structure that allows storing multiple values of the same type in a single variable. Unlike a normal variable that can only contain one value, an array can store multiple values, called elements. These elements are organized in a specific order and are accessed through numerical indices, starting from 0.

 

Array Declaration and Creation

 

  • Declaration: Involves specifying the data type that the array will contain and giving it a name.
  • Creation: Involves allocating memory for the array, defining how many elements it can store.
  • Declaration and Creation in a Single Line: To simplify and make the code more efficient, an array can be declared and created in a single line.

 

Assigning Values to an Array

 

Values are assigned to array elements using their index. This allows accessing and modifying each array element directly through its index.

 

Assigning Values in a Single Line

 

It’s possible to assign values to an array directly when declaring and creating it, resulting in cleaner and more readable code.

 

Traversing Arrays Using Loops

 

To access each element of an array, loops such as the for loop are used. This type of loop is efficient for iterating over each array element and performing various operations with them.

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