Java Reference
In-Depth Information
The width denotes the minimum number of characters to be written to the output. If the length of the string
representation of the argument is less than the width value, the result will be padded with spaces. The space padding
is performed to the left of the argument value. If '-' flag is used, space padding is performed to the right. The value
of width alone does not decide the content of the result. The values of width and precision together decide the final
content of the result.
The precision denotes the maximum number of characters to be written to the output. The precision is applied
to the argument before the width is applied. You need to understand the consequences of applying the precision before the
width. If the precision is less than the length of the argument, the argument is truncated to the length that is equal to
the precision, and space padding is performed to match the length of the output to the value of the width. Consider
the following snippet of code:
System.out.printf("'%4.1s'", "Ken");
' K'
The argument is "Ken" and the format specifier is "%4.1s" , where 4 is the width and 1 is the precision. First, the
precision is applied that will truncate the value "Ken" to "K" . Now, the width is applied, which states that a minimum
of four characters should be written to the output. However, after the precision is applied, you have only one character
left. Therefore, "K" will be left padded with three spaces to match the width value of four.
Consider the following snippet of code:
System.out.printf("'%1.4s'", "Ken");
'Ken'
The argument value is "Ken" and the format specifier is "%1.4s" where 1 is the width and 4 is the precision.
Because the precision value of 4 is greater than the length of the argument, which is 3, there is no effect of the
precision. Because the width value of 1 is less than the width of the result after precision is applied, there is no effect of
the width value on the output.
The following are some examples of using Boolean, string and hash code formatting conversions. Note that the
hash code formatting conversion ( 'h' and 'H' ) outputs the hash code value of the argument in a hexadecimal format.
These examples also demonstrate the effect of using the uppercase variants of the conversions.
// Boolean conversion
System.out.printf("'%b', '%5b', '%.3b'%n", true, false, true);
System.out.printf("'%b', '%5b', '%.3b'%n", "Ken", "Matt", "Lola");
System.out.printf("'%B', '%5B', '%.3B'%n", "Ken", "Matt", "Lola");
System.out.printf("%b %n", 1969);
System.out.printf("%b %n", new Object());
'true', 'false', 'tru'
'true', ' true', 'tru'
'TRUE', ' TRUE', 'TRU'
true
true
Search WWH ::




Custom Search