,

Program Output – Basics of Java Programming

1.9 Program Output

Data produced by a program is called output. This output can be sent to different devices. The examples presented in this book usually send their output to a terminal window, where the output is printed as a line of characters with a cursor that advances as the characters are printed. A Java program can send its output to the terminal window using an object called standard out. This object, which can be accessed using the public static final field out in the System class, is an object of the class java.io.PrintStream. This class provides methods for printing values. These methods convert values to their text representation and print the resulting string.

The print methods convert a primitive value to a string that represents its literal value, and then print the resulting string.

Click here to view code image

System.out.println(2022);                               // 2022

An object is first converted to its text representation by calling its toString() method implicitly, if it is not already called explicitly on the object. The print statements below will print the same text representation of the Point2D object denoted by the reference origin:

Click here to view code image

Point2D origin = new Point2D(0, 0);
System.out.println(origin.toString());                  // (0,0)
System.out.println(origin);                             // (0,0)

The toString() method called on a String object returns the String object itself. As string literals are String objects, the following statements will print the same result:

Click here to view code image

System.out.println(“Stranger Strings”.toString());      // Stranger Strings
System.out.println(“Stranger Strings”);                 // Stranger Strings

The println() method always terminates the current line, which results in the cursor being moved to the beginning of the next line. The print() method prints its argument to the terminal window, but it does not terminate the current line:

Click here to view code image

System.out.print(“Don’t terminate this line!”);

To terminate a line without printing any values, we can use the no-argument println() method:

System.out.println();

Related Posts