Home : Course Map : Chapter 5 : Java : Tech :
System.out.printf() - J2SE5.0
JavaTech
Course Map
Chapter 5
File/Package/Import
  Demo 1
  Demo 2
Access/Visibility
final & Constants
Static Import
Jar Files
  Demo 3
Applet Directories
3rd Party Packages
CLASSPATH
javadoc
CodingConventions
Exercises

    Supplements
Scope
Debug Techniques
Java Runtime
Class Class
JVM Instructions 2
JVM Processing
pack200

     About JavaTech
     Codes List
     Exercises
     Feedback
     References
     Resources
     Tips
     Topic Index
     Course Guide
     What's New

The java.text.Format subclasses offer limited formatting capabilities and are rather clumsy compared to the C language printf() function, which provides a wide range of formatting options combined with output operation.

To satisfy the demands of programmers for such a facility and to facilitate the porting of C programs to Java, J2SE 5.0 comes with the class java.util.Formatter, which can both format numerical output into a string and send the string to a file or other destination (we discuss I/O in Chapter 9).

Numerical values are formatted according to format specifiers like those for the printf() function in C.

Furthermore, J2SE 5.0 added a printf() method to the PrintStream class (see Chapter 9). So now you can use System.out.printf() to send formatted numerical output to the console. It uses a java.util.Formatter object internally and so emulates the printf() function in C.

In Chapter 9 we return to the java.util.Formatter class in the context of Java I/O. Here we introduce the printf() method so that you can begin to take advantage of it.

The simplest of the overloaded versions of the method goes as

  printf (String format, Object... args)

The "..." indicates the varargs functionality (also referred to as variable arity methods), which we noted in Chapter 1 was introduced with J2SE 5.0. It allows a method to accept a variable number of arguments. We note that the arguments can be primitives as well as object references, e.g. the wrappers for the primitives.

The format argument is a string in which you embed specifier substrings that indicate how the arguments appear in the output. For example,

  double pi = Math.PI;
  System.out.printf ("pi = %5.3f%n", pi);

results in the console output

  pi = 3.142

The format string includes the specifier "%5.3f" that is applied to the argument. The '%' sign signals a specifier. The width value 5 requires at least five characters for the number, the precision value 3 requires three places in the fraction, and the conversion symbol 'f' indicates a decimal representation of a floating-point number.

A specifier needs at least the conversion character, of which there are several besides 'f'. Some of the other conversions include

'd' - decimal integer
'o' - octal integer
'e' - floating-point in scientific notation

There are also special conversions for dates and times (calendar and time classes are discussed in Chapter 10). The general form of the specifier includes several optional terms:

  %[argument_index$][flags][width][.precision]conversion

The argument_index indicates to which argument the specifier applies. For example, %2$ indicates the second argument in the list. A flag indicates an option for the format. For example, '+' requires that a sign be included and '0' requires padding with zeros. The width indicates the minimum number of characters and the precision is the number of places for the fraction.

There is also one specifier that doesn't correspond to an argument. It is "%n" which outputs a line break. A "\n" can also be used in some cases, but since "%n" always outputs the correct platform-specific line separator, it is portable across platforms whereas"\n" is not.

We don't have space here for more than this brief overview of the new format tools. The Java API Specifications for J2SE 5.0 provides a lengthy description of the java.util.Formatter class and all of the specifiers and their options.

The following program provides several examples of printf().

PrinfDemo.java

import java.applet.*;

/** Illustrate use of the DecimalFormat class **/
public class PrintfDemo extends Applet
{
  /** Illustrate several output formats with printf() **/
  public void init () {

    double q = 1.0/3.0;
    // Print the number with 3 decimal places.
    System.out.printf ("1.0/3.0 = %5.3f %n", q);

    // Increase the number of decimal places
    System.out.printf ("1.0/3.0 = %7.5f %n", q);

    // Pad with zeros.
    q = 1.0/2.0;
    System.out.printf ("1.0/2.0 = %09.3f %n", q);

    // Scientific notation
    q = 1000.0/3.0;
    System.out.printf ("1000/3.0 = %7.2e %n", q);

    // More scientific notation
    q = 3.0/4567.0;
    System.out.printf ("3.0/4567.0 = %7.2e %n", q);

    // Negative infinity
    q = -1.0/0.0;
    System.out.printf ("-1.0/0.0 = %7.2e %n", q);

    q = 0.0/0.0;
    // NaN
    System.out.printf ("0.0/0.0 = %5.2e %n", q);

    // Multiple arguments
    System.out.printf ("pi = %5.3f, e = %5.4f %n", Math.PI, Math.E);

    double r = 1.1;
    // User the argument index to put the argument values into
    // different locations within th string.
    System.out.printf ("C = 2 * %1$5.5f * %2$4.1f, "+
                       "A = %2$4.1f * %2$4.1f * %1$5.5f %n",
                         Math.PI, r);

  }

  /** Paint message in Applet window. **/
  public void paint (java.awt.Graphics g) {
     g.drawString ("Test printf()",20,20);
  }

  /** Can also run this program as an application.
    * No windowing needed so just run the applets
    * init () function.
   **/
  public static void main (String [] args) {
    PrintfDemo obj = new PrintfDemo ();
    obj.init ();
  }

} // class PrintfDemo

Output of this program:

1.0/3.0 = 0.333
1.0/3.0 = 0.33333
1.0/2.0 = 00000.500
1000/3.0 = 3.33e+02
3.0/4567.0 = 6.57e-04
-1.0/0.0 = -Infinity
0.0/0.0 = NaN
pi = 3.142, e = 2.7183
C = 2 * 3.14159 * 1.1, A = 1.1 * 1.1 * 3.14159

 

References and Web Resources

Last update: Jan. 31, 2005

            Tech
DecimalFormat
  Demo 1
  Demo 2

System.out.printf
  Demo 3
CJ Format Class
  Demo 4   Demo 5
Other Format Tools

Immutable Complex
Exercises

           Physics
Interpolation
Integration
  Demo 1
Simpson Rule
  Demo 2
Exercises

  Part I Part II Part III
Java Core 1  2  3  4  5  6  7  8  9  10  11  12 13 14 15 16 17
18 19 20
21
22 23 24
Supplements

1  2  3  4  5  6  7  8  9  10  11  12

Tech 1  2  3  4  5  6  7  8  9  10  11  12
Physics 1  2  3  4  5  6  7  8  9  10  11  12

Java is a trademark of Sun Microsystems, Inc.