Printing and Commenting

To begin, this lesson will take a look at the Hello world! program you created in the previous lesson. We will cover important points about the structure of that program. Then, we will discuss how you can print whatever text you want to the console. Finally, we will talk about commenting your code.

Hello World!

Go ahead and create a new Java Repl. I suggest you call it PrintingAndCommenting. Just like in the last lesson, there should be a little bit of autogenerated code:

class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}

To a beginner, this program looks very intimidating. Don't worry thoughβ€”you don't have to understand any of it yet. We won't even cover what some parts of it do until several lessons later. With that in mind, there are a few things that are important for you to take note of. One important idea is syntax highlighting. Practically all editors, including Repl, make different parts of your code appear in different colors. This is to help you identify sections of code and easily diagnose errors.

Another important thing to notice is the indentation. Inside each set of curly braces ({ and }), the level of indentation increases by one unit. In this case, one unit is equal to two spaces since that is the default setting for Repl.it. The specific amount of indentation is unimportant (programmers often disagree about one tab, two spaces, three spaces, four spaces, or eight spaces), but it is critical that within a program, you are consistent. Properly indenting your code makes it much easier to read.

All Java programs begin with a main method. The main method starts on the second line where it says public static void main(String[] args) {. Everything after the { but before the } is inside the main method. This means that the only thing currently inside the main method is the third line which reads System.out.println("Hello world!");.

The third line is an example of a statement. Statements in Java are specific instructions. You can think of them as commands to the computer. For instance, the statement on the third line tells Java to put the text from inside the quotes in the console. In this case, the text is Hello world!, so Hello world! gets printed in the console.

All statements inside the main method are executed in order. Currently, there is only one statement inside the main method, so it gets executed first, but if there were another statement before it, then that would be executed first.

Statements always end in a semicolon (;). If you try removing the semicolon at the end of the third line and running the program, it will not compile. Repl.it will print an error message in the console instead:

Main.java:3: error: ';' expected
    System.out.println("Hello world!")
                                      ^
1 error
compiler exit status 1

This error is fairly simple, but reading error messages is an important skill. The first line of the error message is the most important. It says that there is an error in the file Main.java on line 3. The compiler expects a semicolon there, but there isn't one. Then, the error message points to where a semicolon should be at the end of the line. Next, the compiler says there was 1 error in total. If we had multiple errors in our code, that number would be higher. Finally, it says the compiler exited with status code 1. Status codes indicate whether or not the program finished running. If a program exits with status code 0, that means it finished as expected. If a program exits with any nonzero status code, there was an error somewhere that prevented it from finishing properly. Because we are missing a semicolon at the end of line 3, the compiler exited with status code 1.

If you put the semicolon back where the error message tells you, the program will run again, printing Hello world! to the console.

Basic Printing

Now that you have a general idea about how Java programs execute, you can start printing other text to the console. As discussed in the previous section, statements in the main method are executed sequentially. If we want to print Hello world! to the console twice, we just need to duplicate the statement that prints it, and the two statements will be executed one after another. The following program prints Hello world! to the console twice:

class Main {
  public static void main(String[] args) {
    System.out.println("Hello world!");
    System.out.println("Hello world!");
  }
}

The statement System.out.println("Hello world!"); prints whatever is inside the quotation marks to the console. Then, it jumps to the next line. This is why the output of the program looks like this:

Hello world!
Hello world!

A statement similar to println exists which prints the text inside the quotation marks but does not jump to the next line after that. To print just the text inside the quotes, you can write System.out.print("Hello world!");. If we modify our program from above, changing println to print, we get the following output:

Hello world!Hello world!

This output makes sense because there are no newlines involved in the print statement.

As you have probably figured out by now, we can print other text to the console by simply changing what is inside the quotes. Try to figure out what the following program would print to the console (make sure to take whitespace and newlines into account):

class Main {
  public static void main(String[] args) {
    System.out.println("FRC Team 167 is the oldest robotics team in Iowa.");
    System.out.print("It was founded in 1998. ");
    System.out.println("In 2020, the team won the Lake Superior Regional.");
  }
}
Click to reveal the answer
FRC Team 167 is the oldest robotics team in Iowa.
It was founded in 1998. In 2020, the team won the Lake Superior Regional.

The first statement prints the text FRC Team 167 is the oldest robotics team in Iowa. followed by a newline since it is a println statement (println stands for "print line"). The second statement prints It was founded in 1998. . Notice there is a space at the end because there is a space before the closing quotation mark in the statement. Additionally, notice that there is not a newline character at the end because we used print instead of println. As such, the last statement starts printing on the same line the second statement left off on. It prints the text In 2020, the team won the Lake Superior Regional. followed by a newline.

Escape Sequences

Take a look at the following program. Can you guess what it prints to the console?

class Main {
  public static void main(String[] args) {
    System.out.println("MLK said, "The time is always right to do what is right."");
  }
}

The syntax highlighting shows us that something is wrong. We can confirm this by trying to compile the program. The compiler complains about several errors (if you try compiling it yourself, notice that the compiler incorrectly identifies what the error is, so you need to identify and fix it yourself). In this case, the error is that we used a " in the text we were trying to print. The compiler thought that the " at the beginning of MLK's quote signified the end of the text we wanted to print. Then, it encountered a bunch of unknown words outside of quotations marks. It didn't know what to do, so it said there were several errors.

We can get around this error by using escape sequences. These allow us to use special characters in text. The backslash character (\) indicates that we want to start an escape sequence. For instance, we can use \" in our text to print the " character. This means that the correct program to print MLK's quote looks like this:

class Main {
  public static void main(String[] args) {
    System.out.println("MLK said, \"The time is always right to do what is right.\"");
  }
}

If we want to manually insert a newline in a string of text, we can do so using the escape sequence. For instance, consider the following program:

class Main {
  public static void main(String[] args) {
    System.out.println("This\nis\nsome\ntext.");
  }
}

The output of the program looks like this:

This
is
some
text.

Using the escape sequence, you can mimic the behavior of the println statement using print. System.out.println("This is some text."); and System.out.print("This is some text.\n"); are equivalent. However, the println statement is preferred because it is more readable.

To print the backslash character itself, you need to escape the backslash with another backslash. This means that to print \, you must use \\ inside your quotes.

There are several other escape sequences in Java. You have learned the most important ones, but if you're curious, you can check out this website to learn the others.

Comments

Comments allow us to write notes to ourselves in our code. We can use them to explain what code does or why we made a particular decision to do something in a certain way. In small programs like those you are writing right now, they often seem pointless, but in large applications, they are super important for figuring out what is going on. If you ever come back to code you wrote six months ago or if you have to use code someone else wrote, comments help you figure out what the code is doing.

There are three types of comments in Java. The first type is a single-line comment. Single-line comments begin with //. After that, you can write anything you want for the rest of the line, and the compiler will ignore it. For instance, the following program contains a comment explaining what the print statement is doing:

class Main {
  public static void main(String[] args) {
    // This print statement prints newlines using \n
    System.out.println("This\nis\nsome\ntext.");
  }
}

The second type of comment is a multi-line comment. Multi-line comments are enclosed in /* and */. Anything between will be ignored by the compiler. This program showcases a multi-line comment:

class Main {
  public static void main(String[] args) {
    /* This is an example of
       a comment that spans
       multiple lines.
     */
    System.out.println("This\nis\nsome\ntext.");
  }
}

The final type of comment is a special type of multi-line comment called JavaDoc. We won't discuss this now because it requires learning about objects and methods first.

Last updated

Iowa City Robotics 2024