Skip to content

Formatting using PrintStream

Estimated time to read: 2 minutes

We saw the use of the printf method on System.out. System.out is a PrintStream, and we can use the printf or format methods interchangeably.

The official Java Tutorial provides further information on using printf to display information to the console.

Take time to review printf, because you'll be wanting to use it. A lot.

PrintStream Class

The java.io package includes a PrintStream class that has two formatting methods that you can use to replace print and println. These methods, format and printf, are equivalent to one another.

The familiar System.out that you have been using happens to be a PrintStream object, so you can invoke PrintStream methods on System.out.

Thus, you can use format or printf anywhere in your code where you have previously been using print or println. For example,

System.out.format(.....);

The syntax for these two java.io.PrintStream methods is the same:

public PrintStream format(String format, Object... args)

where format is a string that specifies the formatting to be used and args is a list of the variables to be printed using that formatting. A simple example would be

System.out.format("The value of " + "the float variable is " +
     "%f, while the value of the " + "integer variable is %d, " +
     "and the string is %s", floatVar, intVar, stringVar); 

The first parameter, format, is a format string specifying how the objects in the second parameter, args, are to be formatted. The format string contains plain text as well as format specifiers, which are special characters that format the arguments of Object... args. (The notation Object... args is called varargs, which means that the number of arguments may vary.)

Format specifiers begin with a percent sign (%) and end with a converter. The converter is a character indicating the type of argument to be formatted. In between the percent sign (%) and the converter you can have optional flags and specifiers. There are many converters, flags, and specifiers, which are documented in java.util.Formatter

PrintStream Examples

The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character.

int i = 461012;
System.out.format("The value of i is: %d%n", i);

The output is: The value of i is: 461012

PrintStream Overloading

The printf and format methods are overloaded. Each has a version with the following syntax:

public PrintStream format(Locale l, String format, Object... args)

To print numbers in the French system (where a comma is used in place of the decimal place in the English representation of floating point numbers), for example, you would use:

System.out.format(Locale.FRANCE,
    "The value of the float " + "variable is %f, while the " +
    "value of the integer variable " + "is %d, and the string is %s%n", 
    floatVar, intVar, stringVar);