Please enable JavaScript to use CodeHS

Printing in Java

Learn how to print values to the console using Java!

By Evelyn Hunter

Often when creating programs, we want to display information or data to users so that they are able to understand and use that information.

In Java, the easiest way to display information to a user is by using System.out.println. System.out.println is used to display a variety of data types - like Strings, integers, and objects - to the terminal console. To use System.out.println, we can simply include the value or variable we’d like displayed to the console as a parameter in the print function:

String name = karel;
System.out.println("Welcome to CodeHS");   //prints Welcome to CodeHS
System.out.println(name);               //prints karel
Plain text

Writing this program in a Java file requires a few additional lines of code:

public class Welcome
{
    public static void main(String[] args)
    {
        String name = karel;
        System.out.println("Welcome to CodeHS");
        System.out.println(name);
    }
}
Plain text

There are a few key parts to pay attention to here:

  • The code that we want to execute is written inside a function called main. Java always looks to the main function as a place to start the program execution.

  • The main function always has this header:

      public static void main(String[] args)
    Plain text
  • The main method exists inside of something called a class. A class is a file that can be executed by Java and run in a Java Virtual Machine. The class should encompass all other code in the file.

Practice

Try printing out your name and where you live!

Print vs Println

When using the System class, there are two different ways that we can print output: println and print. The big difference between these two is that println will display the message on a new line, while the printstatement will print the message on the same line.

When two println statements are used together,

System.out.println(“Hello world!”);  
System.out.println(“Hello world!”);
Plain text

the result is:

Hello world!
Hello world!
Plain text

When two print statements are used

System.out.print(“Hello world!”);
System.out.print(“Hello world!”);
Plain text

the result is:

Hello world!Hello world!
Plain text

When println is called twice, the output is displayed on two separate lines. The print statement, however, displays the output on the same line.

If you were to use println followed by print, the print statement will appear on the next line, but if the print statement comes before the println, the statement will stay on the same line.

Take a look at this example:

An easy way of thinking about this, is that println affects the subsequent line, not the ones that comes before it!

Practice

Print your full name to the console using at least 2 print statements and 1 println statement.