Java Reference
In-Depth Information
// String conversion
System.out.printf("'%s', '%5s', '%.3s'%n", "Ken", "Matt", "Lola");
System.out.printf("'%S', '%5S', '%.3S'%n", "Ken", "Matt", "Lola");
// Use '-' flag to left-justify the result. You must use width when you specify the '-' flag
System.out.printf("'%S', '%-5S', '%.3S'%n", "Ken", "Matt", "Lola");
System.out.printf("%s %n", 1969);
System.out.printf("%s %n", true);
System.out.printf("%s %n", new Object());
'Ken', ' Matt', 'Lol'
'KEN', ' MATT', 'LOL'
'KEN', 'MATT ', 'LOL'
1969
true
java.lang.Object@de6f34
// Hash Code conversion
System.out.printf("'%h', '%5h', '%.3h'%n", "Ken", "Matt", "Lola");
System.out.printf("'%H', '%5H', '%.3H'%n", "Ken", "Matt", "Lola");
System.out.printf("%h %n", 1969);
System.out.printf("%h %n", true);
System.out.printf("%h %n", new Object());
'12634', '247b34', '243'
'12634', '247B34', '243'
7b1
4cf
156ee8e
If you pass a value of a primitive type as an argument to the format() method of the Formatter class (or the
printf() method of the PrintStream class), the primitive type value is converted to a reference type using an
appropriate type of wrapper class using the autoboxing rules. For example, the statement
System.out.println("%s", 1969);
will be converted to
System.out.println("%s", new Integer(1969));
Writing a Custom Formatter
The Formatter class supports custom formatting through 's' and 'S' conversions. If the argument implements
java.util.Formattable interface, the 's' conversion calls the formatTo() method on the argument to get the
formatted result. The formatTo() method is passed the reference of a Formatter object, flags, width, and precision
values that are used in the format specifier. You can apply any custom logic inside the formatTo() method of the class
to format the objects of your class. Listing 13 - 6 contains the code for a FormattablePerson class, which implements
the Formattable interface.
 
Search WWH ::




Custom Search