Other Conversion Characters
The remaining conversion characters are b, B, h, H, % and n. These are described in Fig. 28.10.
Conversion character |
Description |
---|---|
b or B |
Print "true" or "false" for the value of a boolean or Boolean. These conversion characters can also format the value of any reference. If the reference is non-null, "TRue" is output; otherwise, "false" is output. When conversion character B is used, the output is displayed in uppercase letters. |
h or H |
Print the string representation of an object's hash code value in hexadecimal format. If the corresponding argument is a null reference, "null" is printed. When conversion character H is used, the output is displayed in uppercase letters. |
% |
Print the percent character. |
n |
Print the platformspecific line separator (e.g., on Windows or on UNIX/LINUX). |
Lines 910 of Fig. 28.11 use %b to print the value of boolean values false and TRue. Line 11 associates a String to %b, which returns true because it is not null. Line 12 associates a null object to %B, which displays FALSE because test is null. Lines 1314 use %h to print the string representations of the hash code values for strings "hello" and "Hello". These values could be used to store or locate the strings in a Hashtable or HashMap (both discussed in Chapter 19, Collections). Note that the hash code values for these two strings differ because one string starts with a lowercase letter and the other starts with an uppercase letter. Line 15 uses %H to print null in uppercase letters. The last two printf statements (lines 1617) use %% to print the % character in a string and %n to print a platformspecific line separator.
Figure 28.11. Using the b, B, h, H, % and n conversion characters.
(This item is displayed on page 1336 in the print version)
1 // Fig. 28.11: OtherConversion.java 2 // Using the b, B, h, H, % and n conversion characters. 3 4 public class OtherConversion 5 { 6 public static void main( String args[] ) 7 { 8 Object test = null; 9 System.out.printf( "%b ", false ); 10 System.out.printf( "%b ", true ); 11 System.out.printf( "%b ", "Test" ); 12 System.out.printf( "%B ", test ); 13 System.out.printf( "Hashcode of "hello" is %h ", "hello" ); 14 System.out.printf( "Hashcode of "Hello" is %h ", "Hello" ); 15 System.out.printf( "Hashcode of null is %H ", test ); 16 System.out.printf( "Printing a %% in a format string " ); 17 System.out.printf( "Printing a new line %nnext line starts here" ); 18 } // end main 19 } // end class OtherConversion
|
Common Programming Error 28.2
Trying to print a literal percent character using % rather than %% in the format string might cause a difficult-to-detect logic error. When % appears in a format string, it must be followed by a conversion character in the string. The single percent could accidentally be followed by a legitimate conversion character, thus causing a logic error. |