The Coder's Handbook

Console Output

PRINTING

Using Print


When writing Java programs, you will often want to print out information to the user. This information is displayed in a text window known as the console.


Let’s start with an example program. Below is the code for a very simple Java program.


Code:

public class Hello

{

public static void main(String[] args)

{

System.out.print("Hello World");

}

}


Output:

Hello World


What does this code do? Before we talk about printing, let’s review the first two lines.


  • The first line specifies the name of the class our code belongs to. The name of this class is Hello. In Java, everything belongs to a class.


  • The second line is the method header for our only method in this program. This is a special method called main. Every program must have a main method, and it is the first method to execute when you run a Java program.


The real action happens with the only statement in the program, repeated below:

System.out.print("Hello World");


This line of code prints out the text “Hello World” to the console. This text is called a string literal, which just means a set of characters that won’t change. We use quotes to show we want to print this exact phrase, but the quotes themselves are not printed. This helps the compiler tell that we’re not trying to use the name of a variable.


Using Println


The print command has two versions. We have already seen how to simply print text. If we do this multiple times, however, it will put all of our text on a single line. It won’t even add spaces!


If we want to print text, then make sure the next phrase will be on a new line, we use a slightly different version of the print command:


Code:

System.out.println("Hello");

System.out.println("World");


Output:

Hello

World


History Fact: The "print" command outputs to the screen, but is named after the ancient practice of putting ink on paper to share information.






Hello, World is the traditional "first program" in any language. We continue this tradition in our class, because Mr. M clearly isn't very creative.

ESCAPE CHARACTERS

The Special Cases


You can print almost anything in a text string… almost. Sometimes, you’ll want to print a special character. For instance, you can’t print a new line by hitting enter. That’d just add a line in your editor!


To solve this problem, Java has escape characters. These are special codes that start with a backslash. When you run your project, they’ll output the desired formatting. Some common escape characters are:


  • New Line \n

  • Tab \t

  • Double Quote \”

  • Backslash \\


Here’s some example code using all of the above escape characters, and what the output looks like.

Code:

System.out.print("Hey! \n A wise man once said: \t \"Never save your work to the C:\\ drive.\"");


Output:

Hey

A wise man once said: “Never save your work to the C:\ drive”

RESOURCES