Learn Java Easy. Chapter 2. Chani’s Disappearance / Displaying data in console

Learn Java Easy. Chapter 2. Chani’s Disappearance / Displaying data in console

Do you remember when I said I was going to have a party at my house? Well, it was a huge success. I’m not sure how many people were there, but more and more people kept showing up. I didn’t know half of them, but that didn’t worry me. It was all about having a good time.

Before bringing guests home, we like to be cautious, so we have a routine. Hours before the attendees start arriving, we store all our valuables in a closet located in Chani’s room. The closet is secured with a padlock, and only Chani has the key. This way, we feel safer in case things get out of control. The next day, we wake Chani up, she opens the closet, and we retrieve our precious belongings. Then we eat something and spend almost the entire afternoon lying on the couch watching some TV series. It’s a big part of our student routine.

Party aftermath
The morning after the party

The problem is that this time everything was different. The morning after the party, everything was chaos. It was much messier than usual, and there were drink spills everywhere. Not to mention the incredible number of bottles and glasses scattered throughout all the rooms.

I woke up around two in the afternoon, quite hungry. I went to the kitchen and opened the fridge. I discovered that, unfortunately, there was nothing to eat, and that greatly affected my mood. Then I started to consider my options. Going out to buy food was completely out of the question. I was very tired and didn’t feel like moving. Ordering food seemed like the most sensible option, but I wasn’t exactly sure what I wanted.

While deciding, I lay down on the couch and texted my roommates. I didn’t want to eat alone, and besides, I thought they would probably be hungry when they woke up too. After a few minutes, Rich came out of his room. He had read the message and wanted pizza. Chani didn’t respond, but we ordered for him anyway.

Pizza delivery

The pizzas finally arrived around three-thirty in the afternoon. Chani showed no signs of life, so we didn’t wake him up. We ate our pizza and chatted for a while. Although we had nothing to do, we didn’t feel like starting to clean up. We didn’t feel like sleeping more either.

We were starting to get a bit bored and wanted our laptops. The only problem was that they were in Chani’s closet. We didn’t wait much longer before deciding to wake him up. We knocked on his door several times but got no response. After a few minutes, we decided to go in.

As we crossed the doorway, we looked at each other in surprise. Chani wasn’t there, but the strangest thing was that his room was completely tidy. It was very odd because it contrasted with the rest of the house, which looked like a pigsty. We were very confused, so we tried calling him, but got no answer.

We didn’t give it much more thought. We assumed he was fine; the only annoyance was that we didn’t have our computers and didn’t know what to do. We sat on the couch and, after a few minutes, Rich started talking. He asked me about my Java learning. I told him I hadn’t made any progress since the last lesson, so he offered to continue with the classes right then and there.

Display data in our console

Before moving forward, you need to understand the stages involved in developing a Java program or application. From when you start writing the code until the completion of the project.

  1. Writing the source code: The process begins when the programmer writes the code in Java language. This is done using a text editor or an Integrated Development Environment (IDE) such as IntelliJ IDEA or Eclipse. The source code follows a specific structure and ‘grammar’.
  2. Saving the source file: When the code is ready, it is saved in a file with the ‘.java’ extension. This file includes all the necessary instructions for the program to function correctly.
  3. Code compilation: The next step is to compile the source code using a Java compiler. This takes the ‘.java’ file and converts it into code called ‘bytecode’. This file is executable on any system that has the Java Virtual Machine (JVM) installed.
  4. Generation of .class files: After compilation, one or more files with the ‘.class’ extension are generated, containing the bytecode. These files will be the ones executed by the JVM.
  5. Program execution: Finally, with the generated bytecode files, the program can be executed using the JVM. The JVM interprets the bytecode and carries out the operations defined in the code that was manually written by the programmer.

At this point, you don’t need to memorize these steps. Our IDE will take care of performing all these steps except the first one – writing the code. But it’s interesting to know the complete process.

Additionally, this has helped us introduce the following two terms:

IDE, or Integrated Development Environment: IDE stands for Integrated Development Environment. This is a software tool that contains everything needed for software application development. It can be described as a ‘command center’ for programmers, containing various useful tools and features in one place.

Java Compiler: This is a tool that translates human-readable source code (the code we have written) into a machine-understandable format. This allows Java code to be portable and run on different platforms without requiring modifications. Without the compiler, we couldn’t transform our ideas into functional applications.

Displaying text and variables in the console

Data Output Importance

In the general programming process, data output is absolutely necessary as it is the main way in which the program can communicate results and its updated status to us. Without visual output, we wouldn’t be able to know what’s happening, whether the program is following our instructions exactly, or if something isn’t working as it should. Most of the time, programmers work based on trial and error, which is why constantly seeing the results is vital. For a novice programmer, it’s even more important since seeing the result of the lines we write will help us learn and understand what happens when we write our syntax.

Common Console Output Uses

  • User Interaction – The console allows interaction with the user by requesting information and displaying results. This interaction is fundamental in basic programs and is an excellent way to teach input and output concepts.
  • Displaying Calculation Results – Presenting the results of mathematical operations, algorithms, or logical processes is one of the basic functions of any program.
  • Feedback in Long Processes – During the execution of time-consuming processes, providing feedback in the console helps the user understand that the program is still running.
  • Code Debugging – Printing variable values and states helps programmers understand how the program is working and identify possible errors.
  • Demonstrations and Educational Examples – Examples that print results to the console are essential for teaching basic programming concepts in a visible and tangible way.

Using System.out.println and System.out.print

We’re going to see how to use a line of code that allows us to display data in our IDE’s console. For this, we can use two commands: println and print.

If you already have some programming experience or have looked for educational material elsewhere, you’ve probably encountered the most famous programming exercise of all time. It consists of displaying the phrase ‘hello world’ in our console. The answer is:

System.out.println(“Hello world”);

It always follows the same structure, System.out.println();

In this specific case, we use double quotes since it’s a text line. We can also display variables that we have previously declared and assigned a value to. Let’s look at an example. Below you will see an int variable called total and we’ve already assigned it a value, in this case 9. We can print it to the screen as follows:

int total = 9;
System.out.println(total);

As mentioned earlier, we can use both print and println, but there is a significant difference between them:

  • System.out.println adds a new line after printing what you specify. It’s like adding a line break after displaying something.
  • System.out.print simply prints what you specify without adding a line break at the end. It’s like writing in a continuous line.

String Concatenation

We can display variable operations and even combine them with text. Imagine that we have declared two int variables ‘a’ and ‘b’. We have assigned them the values 5 and 7 respectively.

int a = 5;
int b = 7;

Then we ask to display the following text: ‘The result of multiplying a and b is =’. Finally, the result of that multiplication.

System.out.println(“The result of multiplying a and b is = ” + a * b);

As you can see, after showing the text we have used the + symbol to join it. (‘text ‘ + result).

We could have done it in the following way, which might be easier to understand:

System.out.println(“The result of multiplying a and b is = ” + (a * b));

Right after the = symbol, we left a space so that, when displayed in the console, there’s a gap. Although we could have done it the following way.

System.out.println(“The result of multiplying a and b is =” + ” ” + (a * b));

I have used + ‘ ‘ + to create a space.

When combining text and numeric data it’s not very useful, but if we want to display two numeric variables and need them to be separated, we’ll use this trick.

Let’s look at another example, but this time with additions.

If we want to add variables a and b from the previous exercise, we’ll simply do it this way:

System.out.println(a+b);

But we might just need both of them to be displayed separately in the console, one after the other. In that case, we’ll do it like this:

System.out.println(a+ ‘ ‘ +b);

Of course, we can also use subtraction and division symbols (- and /) depending on what we need.

Changing the Font Color

It’s possible that at some point we may need the color appearing in our console to be different from the default white. We can achieve this very easily. We simply need to insert a color code into our line from those shown in the following table:

ColorCode
BLACK“\033[30m”
RED“\033[31m”
GREEN“\033[32m”
YELLOW“\033[33m”
BLUE“\033[34m”
PURPLE“\033[35m”
CYAN“\033[36m”
WHITE“\033[37m”

We’ll do it this way:

System.out.println(“\033[31m” + “The result of multiplying a and b is =” + ” ” + (a * b));

We insert the code right before the part that we need to change color. From that point until the end of the line, it will be displayed in the new color. If we need two or more colors, we’ll insert the corresponding codes right before the parts that should be shown in that specific shade.

System.out.println(“\033[31m” + “The result of multiplying a and b is =” + ” ” + “\033[34m” + (a * b));

Comments in our code that don’t print

The double forward slashes ‘//’ are used in Java to indicate a single-line comment. This means that any text after the double slashes in that line will be ignored by the Java compiler and won’t affect the program’s execution.

// This is a single-line comment

int age = 25; // This line declares a variable called age and assigns it the value 25

In this case, comments are used to make annotations in the code that help understand what each part of the program does. They are also useful for temporarily disabling a line of code without having to completely delete it.

Limiting data output to two decimal places

Note: For now, you won’t need to limit the number of decimal places in any exercise. In fact, if you’re new to Java, you should skip this section. The reason I’m including it here is because some people might find it useful and don’t want their operations to show a long string of decimal places.

However, even if it’s not useful to you right now, remember that you have this information here and can come back to it when you need it. On the other hand, if you feel confident enough, you can try to limit the decimal places in your exercises.

Methods for limiting decimals

In Java, you can use the DecimalFormat class to easily limit the number of decimal places to two. Here’s an example:

import java.text.DecimalFormat;

public class Main {
    public static void main(String[] args) {
        double num = 3.14159;
        DecimalFormat df = new DecimalFormat(“#.00”);
        System.out.println(“Number with two decimals: ” + df.format(num));
        // Output: 3.14
    }
}

Another way to limit decimals to two places in Java is by using the printf() function or String.format().

Example with printf():

public class Main {
    public static void main(String[] args) {
        double num = 3.14159;
        System.out.printf(“Number with two decimals: %.2f”, num);
        // Output: 3.14
    }
}

Example with String.format():

public class Main {
    public static void main(String[] args) {
        double num = 3.14159;
        String result= String.format(“%.2f”, num);
        System.out.println(“Number with two decimals: ” + result);
        // Output: 3.14
    }
}

When we cover the topic of random numbers, I’ll teach you another different method, which for me is the simplest and the one I always use.

Summary of What You’ve Learned

In Java, to display information in the console, we use the System.out.println and System.out.print commands. Both display data on the screen, but there’s an important difference: System.out.println automatically adds a line break after printing, while System.out.print doesn’t, keeping the next output on the same line.

For example, if we want to display text like ‘Hello world’ in the console, we write:

System.out.println(“Hello world”);

If we want to display a variable, like total, which has a value of 9, we write:

int total = 9;
System.out.println(total);

We can also perform operations and combine text with variables. For example, if we have two variables a and b with values 5 and 7 respectively, and we want to show the result of their multiplication along with text, we do it like this:

int a = 5;
int b = 7;
System.out.println(“The result of multiplying a and b is = ” + (a * b));

Additionally, we can change the text color in the console by adding color codes before the text we want to change. For example, to display text in red, we write:

System.out.println(“\033[31m” + “This text will be red”);

Finally, to make annotations in our code that won’t print to the console and are only meant for us or other programmers reading the code, we use double forward slashes ‘//’ to indicate a single-line comment.

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