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

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

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

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

I was silent for a few seconds. I felt myself getting angry little by little, until I started cursing and stumbling, as I wanted to express many things at once. At one point, one of the guards approached and asked me to calm down. The truth is that it was a good release. After that, I felt much calmer and willing to see what he had to say.

Besides being angry, I was very curious. All the answers I had been longing for weeks were right in front of me. I wanted to know exactly what kind of trouble Chani was in, why he had done it, and especially why he had incriminated me. Maybe it had all been a mistake. Perhaps he was sorry and wanted to exonerate me. Numerous questions ran through my head, and I didn’t know which one to start with.

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.

I found it quite hard to believe, so I asked him how he was so sure. Then he told me that Chani had sent him to tell me the true story. I got angry again. I told him that if he knew where Chani was, he should say it or he would be guilty of covering for him. Again, the guard came to reprimand me.

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 plan of the real culprits: Rich and Fernando.

It seems that the day before the party, Chani came 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 time, 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 in the living room, and it was at that moment when he realized they were using my computer. Seeing themselves cornered, they had no choice but to offer him to participate in the crime. They explained the plan in detail, including the part where, if something bad happened, they would blame me.

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

During the night, they got that answer. But it wasn’t what they expected. So things got 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 such a thing to me. After a few seconds of silence, he looked at me intently and asked if I believed him. I replied that I didn’t, and then he took 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 him, but there was a lot of noise at the party and Rich is very clever. From that conversation, only the part where he tells him to leave the city that same night can be distinguished.

It seems that Chani has a plan to unmask Rich, but he might need my help. I don’t know how I can help from here locked up. Perhaps during one of his visits, I can get a confession or at least some information. The bad thing about being cut off is not only 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 he has always seemed very worried. I didn’t expect it, 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 classes. He seems especially motivated. He told me that once he learns what arrays are, he will be able to explain exactly how they help officials with the prison software. For now, I don’t want to tell him anything about my personal situation. I know he would be worried. So for now, I put on a good 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 indicating what type of data it will hold and how many elements it will store. For example, an integer array (int) with a size of 5 can hold five integer numbers. Arrays in Java start counting from 0, so the first element is at position 0.

Importance of Arrays in Programming

  • They allow organizing data in a structured way, which facilitates 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 accessed quickly using their index, which is crucial for applications that need fast and frequent data read or modification operations.
  • Additionally, arrays allow performing common operations such as iteration, searching, sorting, and data manipulation easily. Many algorithms and data structures are based on arrays due to their simplicity and efficiency, such as sorting and searching algorithms.
  • In real 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

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

Step 1: Declare the array

type[] arrayName;

Examples:

int[] numbers; // Declaration of an integer array

String[] names; // Declaration of a string array

double[] temperatures; // Declaration of a double array

Step 2. Create the array

arrayName = new type[size];

Examples:

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 will almost never use this structure. It’s much simpler, faster, and more effective to do everything on the same line. Besides, it will be much easier for you to remember.

Declaration and Creation in One 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 of our array has a value. For example, if we want to display the 5th position on the screen, we do it as follows:

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

String[] names = new String[3];

names[0] = “Lucia”; names[1] = “Pedro”; names[2] = “Lueds”;

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 “” “”, we would use ‘ ‘.

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

Assigning Values to Arrays in One Line

Sometimes you’ll come across brackets in arrays. They also serve to assign values to them. This is the structure used for this purpose:

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

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

int[] numbers = {10, 20, 30, 40, 50}; System.out.println(numbers[4]);

Now we continue with our text example. We have three names and we declare and assign values to an array in one line.

–      String[] names = {“Lucia”, “Pedro”, “Lueds”};

As you can see, at first glance, this way of creating arrays and assigning values to them is much simpler. The code looks more organized and elegant. Although it’s not all advantages. Without having the position of each element indicated, sometimes we can get lost and 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 simple glance, we can visualize the entire scheme 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 iterating over the elements of an array in a simple and efficient way. The simplest approach for 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]);

              }

       }

}

Note that in all examples, the first position of the loop 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 accessed through numeric indices, starting from 0.

Declaration and Creation of Arrays

  • Declaration: Consists of specifying the data type 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 One 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 element of the array directly through its index.

Assigning Values in One 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 element of the array and performing various operations with them.

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