Tino APCS

Printing Variables Using the System.out Object

The System.out object is automatically created in every Java program. It has methods for displaying text strings and numbers in plain text format on the system display, which is sometimes referred to as the “console.” For example:

Code Sample 3-2

Method System.out.println displays (or prints) a line of text in the console window. When System.out.println completes its task, it automatically positions the output cursor (the location where the next character will be displayed) to the beginning of the next line in the console window (this is similar to pressing the Enter key when typing in a text editor-the cursor is repositioned at the beginning of the next line).

The expression

"number = " + number

from the statement

System.out.println("number = " + number);

uses the + operator to “add” a string (the literal "number = ") and number (the int variable containing the number 5). Java defines a version of the + operator for String concatenation that enables a string and a value of another data type to be concatenated (added). The result of this operation is a new (and normally longer) String. String concatenation is discussed in more detail later on.

The lines

System.out.print("The ");
System.out.println("End!");

of Code Sample 3-2 display one line in the console window. The first statement uses System.out’s method, print, to display a string. Unlike println, print does not position the output cursor at the beginning of the next line in the console window after displaying its argument. The next character displayed in the console window appears immediately after the last character displayed with print.

Note the distinction between sending a String literal, "number = ", versus a variable, number, to the System.out object. A boolean variable will be printed as true or false.

The result (or output) of formulas using Strings may also be printed. Note how the placement of the quotes affects the output.

Dark Mode

Outline