Formatters and Java Print Streams - Format Specifiers (Page 4 of 5 )
The Formatter class and the printf() method inPrintStreamthat depends on it support several dozen format specifiers. In addition to integer and floating-point numbers,Formatter offers a wide range of date and time formats. It also has a few general formatters that can display absolutely any object or primitive data type.
All format specifiers begin with percent signs. The minimum format specifier is a percent sign followed by an alphabetic conversion code. This code identifies what the corresponding argument is to be formatted as. For instance,%fformats a number with a decimal point,%dformats it as a decimal (base-10) integer,%oformats it as an octal integer, and%xformats it as a hexadecimal integer. None of these specifiers changes what the number actually is; they’re just different ways of creating a string that represents the number.
To use a literal percent character in a format string, just double escape it. That is,%%is formatted as%in the output.
To get the platform default line separator, use%n.(\nis always a linefeed regardless of platform.%nmay be a carriage return, a linefeed, or a carriage return linefeed pair, depending on the platform.)
Integer conversions
Integer conversions can be applied to all integral types (specifically, byte, short,int, andlong, as well as the type-wrapper classesByte,Short,Integer,Long, and also thejava.math.BigIntegerclass). These conversions are:
%d A regular base-10 integer, such as 987
%o A base-8 octal integer, such as 1733
%x A base-16 lowercase hexadecimal integer, such as 3db
%X A base-16 uppercase hexadecimal integer, such as 3DB
Example 7-1 prints the number 1023 in all four formats.
Example 7-1. Integer format specifiers
public class IntegerFormatExample {
public static void main(String[] args) { int n = 1023; System.out.printf("Decimal: %d\n", n); System.out.printf("Octal: %o\n", n); System.out.printf("Lowercase hexadecimal: %x\n", n); System.out.printf("Uppercase hexadecimal: %X\n", n); } }