Conversions and Java Print Streams - Character conversions
(Page 2 of 5 )
Character conversions can be applied to char and java.lang.Character objects. They can also be applied to byte, short,int, and the equivalent type-wrapper objects if the integer falls into the range of Unicode code points (0 to 0x10FFFF). These
conversions are:
%c
A lowercase Unicode character
%C
An uppercase Unicode character
Boolean conversions
Boolean conversions can be applied to boolean primitive values and java.lang.Boolean objects. They can also be applied to all object types, in which case they’re considered to be true if the object is nonnull and false if it is null. All other primitive types are considered to be true, regardless of value. These conversions are:
%b
“true” or “false”
%B
“TRUE” or “FALSE”
These conversions are not localized. Even in France, you’ll see “true” and “false” instead of “vrai” and “faux.”
General conversions
There are two more conversions that can be applied to any object and also to primitive types after autoboxing. These are:
%h/%H
The lowercase/uppercase hexadecimal form of the
object’shashCode, or “null” or “NULL” if the object is
null.
%s/%S
The result of invoking the object’sformatTo()
method if it implementsFormattable; otherwise,
the result of invoking itstoString()method, or
“null” if the object is null. With%S, this value is then
converted to uppercase.
Example 7-4 prints a URL (which does not implementFormattable) in all of these formats.
Example 7-4. General format specifiers
import java.net.*;
public class GeneralFormatExample {
public static void main(String[] args) throws MalformedURLException{
URL u = new URL(http://www.example.com/Article.html);
System.out.printf("boolean: %b\n", u);
System.out.printf("BOOLEAN: %B\n", u);
System.out.printf("hashcode: %h\n", u);
System.out.printf("HASHCODE: %H\n", u);
System.out.printf("string: %s\n", u);
System.out.printf("STRING: %S\n", u);
}
}
Here’s the output from running this on a U.S.-localized system:
boolean: true
BOOLEAN: TRUE
hashcode: 79d2cef0
HASHCODE: 79D2CEF0
string: http://www.example.com/ Article.html
STRING: HTTP://WWW.EXAMPLE.COM/ ARTICLE.HTML
Be cautious about uppercasing. URL path components and many other things are case sensitive. HTTP://WWW.EXAMPLE.ORG/ARTICLE.HTML is not the same URL as http://www.example.org/Article.html.
Next: Format Modifiers >>
More Java Articles
More By O'Reilly Media
|
This article is excerpted from chapter seven of Java I/O, Second Edition, written by Elliotte Rusty Harold (O'Reilly, 2006; ISBN: 0596527500). Check it out today at your favorite bookstore. Buy this book now.
|
|