Formatting Output with printf

Precise output formatting is accomplished with printf. [Note: J2SE 5.0 borrowed this feature from the C programming language.] Method printf can perform the following formatting capabilities, each of which is discussed in this chapter:

  1. Rounding floating-point values to an indicated number of decimal places.
  2. Aligning a column of numbers with decimal points appearing one above the other.
  3. Right justification and left justification of outputs.
  4. Inserting literal characters at precise locations in a line of output.
  5. Representing floating-point numbers in exponential format.
  6. Representing integers in octal and hexadecimal format. (See Appendix E, Number Systems, for more information on octal and hexadecimal values.)
  7. Displaying all types of data with fixed-size field widths and precisions.
  8. Displaying dates and times in various formats.

Every call to printf supplies as the first argument a format string that describes the output format. The format string may consist of fixed text and format specifiers. Fixed text is output by printf just as it would be output by System.out methods print or println. Each format specifier is a placeholder for a value and specifies the type of data to output. Format specifiers also may include optional formatting information.

In the simplest form, each format specifier begins with a percent sign (%) and is followed by a conversion character that represents the data type of the value to output. For example, the format specifier %s is a placeholder for a string, and the format specifier %d is a placeholder for an int value. The optional formatting information is specified between the percent sign and the conversion character. The optional formatting information includes an argument index, flags, field width and precision. We define each of these and show examples of them throughout this chapter.

Категории