The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


Printing Variables

You can print the value of a variable using the same commands we used to print Strings.

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");

If you want to get a little tricky, you could 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 pleased 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: It is common practice to use several print commands followed by a println, in order to put multiple values on the same line. But you have to be careful to remember the println at the end. In many environments, the output from print is stored without being displayed until the println command is invoked, at which point the entire line is displayed at once. If you omit println, the program may terminate without ever displaying the stored output!



Last Update: 2011-01-24