Formatting Output

Things To Do First

Things To Do Later

Formatting Console Output

In chapter 4.6 you are introduced to the printf() method. The printf() method is used a little bit differently than print() and println(). The printf() method will take more than one argument or piece of data, unlike print() and println(). The first argument you give printf() is a format string: a string value that contains one or more format specifiers. The second and subsequent arguments are numeric values that will be output using the format specifiers in the output string. For example:

System.out.printf("Print this number: %d", 25);

In this example, a special format specifier %d is used in the first argument. The second argument is the integer value 25. The printf() method will substitute the %d specifier with the value 25. The "%d" format specifier is used to print integer numbers. Integers are formatted with no decimal places and include the thousands separator when appropriate.

Read!
See the notes I left you in chapter 4.6 in Revel - they point out some very important images/diagrams that will help you understand how to easily use the printf() method.

When you give printf() the value you'd like to print, you have to make sure that you always give it the format String first. This format string can contain anything you'd like to print, but any values that you want formatted should be represented by format specifiers. Other format specifiers are shown in Table 4.11 in chapter 4.6.

After you specify the String you want to output, you then specify the value(s) you want formatted. Separate each argument, including the string, with commas. In the above example, the %d in the string will be replaced by the value 25.

If you want to print a decimal value, you can use the %f specifier, which will print a decimal value with 6 digits after the decimal. For example:

System.out.printf("This is a floating point value: %f", 2.345);

You can also format more than one value by including more than one format specifier. You must make sure you include an argument for each specifier:

System.out.printf("The result of %f times %f is %f.", .25, 
	1.1, (.25 * 1.1));

The values and format specifiers match by the order in which they appear. In the example above, the first %f will be the formatted value .25, the second %f will be the formatted value 1.1, and the last %f will be the formatted result of (.25 * 1.1).

You can also specify how many digits after the decimal you'd like to display. Between the % and the "f" of the floating point format specifier, you can include information about the number of spaces a value should take up, and the number of digits that should appear after the decimal. For example:

System.out.printf("This is a nicer decimal value: %4.2f.",
	(.25 * 1.1));

This will output:

This is a nicer decimal value: 0.28.

The format specifier "%4.2f" indicates that a floating point number is displayed in a total of 4 character spaces, including 2 digits after the decimal.

What happens if you try it this way:

System.out.printf("This is a nicer decimal value: %10.2f.",
	(.25 * 1.1));

You'll get the following result:

This is a nicer decimal value:       0.28.

If the first number in the format specifier is more space than you need, extra padding will be added to the left of the value to make up the number of character spaces specified. In our example, we specified 10 spaces, but we only required 4, so 6 extra spaces were added. This can come in handy when you want to line up columns of decimal values:

System.out.println("Some Values:");
System.out.printf("%9.2f\n", 123.45);

// why is there an "f" after the number in the next statement?
// not sure?  take it out and recompile!
System.out.printf("%9.2f\n", 1234f);  

System.out.printf("%9.2f\n", .12);
System.out.printf("%9.2f\n", 1.2);

Try this code! You'll get the following output:

Some Values:
   123.45
  1234.00
     0.12
     1.20

If you want to make your formatted values left-justified instead of right-justified, add a "-" (minus sign or dash) in front of the total space value:

System.out.println("Some Values:");
System.out.printf("Value 1: %-9.2f\n", 123.45);
System.out.printf("Value 2: %-9.2f\n", 1234f);
System.out.printf("Value 3: %-9.2f\n", .12);
System.out.printf("Value 4: %-9.2f\n", 1.2);

Output:

Value 1: 123.45
Value 2: 1234.00
Value 3: 0.12
Value 4: 1.20

For more examples and comments about format specifiers, see Table 4.12 in chapter 4.6 of your textbook.

Note
The System.out.format() method works exactly the same as System.out.printf()! You can use either method, but pick one and stick with it: don't mix and match in the same program.

Exercises

1. What is the output from each of the following print statements?

  1. System.out.printf("%3d", 5);
  2. System.out.printf("%3d", 12345);
  3. System.out.printf("%5.2f", 7.24);
  4. System.out.printf("%5.2f", 7.277);
  5. System.out.printf("%5.2f", 123.456);
  6. System.out.printf("%5.2f", 123.4);
  7. System.out.printf("%-5.2f", 7.277);
  8. System.out.printf("%-5.2f", 123.456);

2. What are the errors in each of the following print statements?

  1. System.out.printf("%d", 23)
  2. System.out.printf("%f", 5);
  3. System.out.printf("%4d", 123.4);
  4. System.out.printf("value 1: %d value 2: d", 5, 10);

[solutions]

Other Formatting Characters

The format specifier itself follows a specific pattern or format:

%[flags][width][.precision]typechar

Each item in [square brackets] is optional.
The named values in the general format above are described as follows:

Common Type Specifiers

Note that I have only included the most common used in this course. For a full list, see the Formatter Class documentation.

Summary of Common Format Type Specifiers
Type Specifier Used For
%sString
%dintegers
%ffloating-points
%ccharacters

In addition, you can use the following specifiers for other values:

%n - a platform-specific line separator (will use the system's default line separator character).

%e, %E - formats the value in exponential notation. If you use the %e, the E in your value is lower-case. If you use %E, the E will be upper-case. There will always be 6 digits after the decimal point in your formatted value, and the exponent will always take minimum 2 digits and will include the sign + or -.

Example (%n line separators included for clarity):
System.out.printf("%e%n", 12345.782983);
System.out.printf("%E%n", 12345.782983);

...will yield the output:
1.234578e+04
1.234578E+04

Flags

There are a number of special flags you can use after the % sign to change how the formatted value will appear. The list below summarizes a few of them.

Note that I have only included the most common used in this course. For a full list, see the Formatter Class documentation.

- (dash, minus sign)
Result is left-aligned (by default, all results are normally right-aligned)
Example:
System.out.printf("%10s%n", "Java");
System.out.printf("%-10s%n", "Java");

...will yield the output:
      Java
Java

0
Allows you to pad a numeric value with leading and trailing zeros.
Example:
System.out.printf("%05d%n", 25);
System.out.printf("%05.2f%n",1.2);

...will yield the output:
00025
01.20

, (comma)
Includes the thousands separator in a value that has more than three digits to the left of the decimal point. The comma character is included in the number of character spaces you've indicated using the width parameter.
Example:
System.out.printf("%,15d%n",10000000);
System.out.printf("%,15.2f%n", 34987.289);

...will yield the output:
     10,000,000
      34,987.29

Exercises

What is the output from each of the following print statements?

  1. System.out.printf("%15e%n", 12.78);
  2. System.out.printf("%-15e%n", 12.78);
  3. System.out.printf("%15s%n", "Programming");
  4. System.out.printf("%-15s%n", "Programming");
  5. System.out.printf("%-7.2f%n", 12.78);
  6. System.out.printf("%-5d%n", 12);
  7. System.out.printf("%03d%n", 0);
  8. System.out.printf("%07.1f%n", 12.78);
  9. System.out.printf("%,010.1f%n", 12345.67);
  10. System.out.printf("%,10d%n", 7777);

[solutions]

Using String.format()

The printf() method is a great way to format console output, but there is an alternative method you can use, which will become especially useful in term 2 when you do GUI programs. You can do this by using the String class's format() method.

String.format() is a method that almost like the printf() method. The String.format() method accepts a string to output and then the list of arguments to format. It then returns the entire string formatted. For example:

String output = 
    String.format("%3.1f x %3.2f is %4.2f", .1, 1.25, (.1*1.25));
System.out.println(output);

In this example the format() method is given the string "%3.1f x %3.2f is %4.2f" and the argument list .1, 1.25, and (.1*1.25). The first two numeric arguments will replace the first and second %3.1f and %3.2f respectively, and the result of (.1*1.25) will replace the %4.2f. The format() method will thus return the string "0.1 x 1.25 is 0.13". This string will be stored in the variable output. Then this string is used in the println() method. The output will appear as:

0.1 x 1.25 is 0.13

Exercises

Complete the code to display the values below on the console. Display one value per line. Each value should be formatted to be right-justified, lined up at the decimal point, and showing only one digit after the decimal point. Use the String.format() function to store your formatted string in a String variable called "output":

35 28.29 143.12 .8899

public class FormatQuestion {

    public static void main(String[] args) {

        // finish this line using String.format():
        String output = 

        System.out.println(output);
    }
}

Your output should appear as:

35.0 28.3 143.1 0.9

[solutions]