Printing variables

You can print the value of a variable using println or print:


class Hello {
  public static void main(String[] args) {
    String firstLine;
    firstLine = "Hello, again!";
    System.out.println(firstLine);
  }
}

This program creates a variable named firstLine, assigns it the value "Hello, again!" and then prints that value. When we talk about “printing a variable," we mean printing the value of the variable. To print the name of a variable, you have to put it in quotes. For example: System.out.println("firstLine");

For example, you can write

  String firstLine;
  firstLine = "Hello, again!";
  System.out.print("The value of firstLine is ");
  System.out.println(firstLine);

The output of this program is
The value of firstLine is Hello, again!
I am happy to report that the syntax for printing a variable is the same regardless of the variable's type.

  int hour, minute;
  hour = 11;
  minute = 59;
  System.out.print("The current time is ");
  System.out.print(hour);
  System.out.print(":");
  System.out.print(minute);
  System.out.println(".");

The output of this program is The current time is 11:59.

WARNING: To put multiple values on the same line, is common to use several print statements followed by a println. But you have to remember the println at the end. In many environments, the output from print is stored without being displayed until println is invoked, at which point the entire line is displayed at once. If you omit println, the program may terminate without displaying the stored output!