Lab: Printf Formatting |
![]() |
Objectives: |
At the conclusion of this lab, students will be able to use a variety of Java formatting techniques to produce formatted output. |
Background: |
The format method of the String class and the printf method of the PrintStream class provide convenient ways to produce formatted output. These methods are new to Java 1.5. Prior to that time, DecimalFormatting or NumberFormatting classes were used to produce formatting objects. These are still present in the language. |
New Terms: |
|
Materials: |
PrintfLab.java PrintfLab.html (documentation page) printf Tutorial |
b B |
If the argument is null, then the result is false. If the argument is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is true. |
s S |
If the argument is null, then the result is null. If the argument arg is null, then the result is "null". If the argument implements Formattable, then the result is the value returned by calling the argument's formatTo method. Otherwise, the result is the value returned by calling the argument's toString method. |
c C |
The result is a Unicode character. |
d | The result is formatted as a decimal integer. |
o | The result is formatted as an octal integer. |
x X |
The result is formatted as a hexadecimal integer. |
e E |
The result is formatted as a decimal number in computerized scientific notation. |
f | The result is formatted as a decimal number. |
g G |
The result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding. |
% | The result is a literal '%'. |
Look at the code in the program PrintfLab.java and predict what it will do. Compile and run the program. Does it work as expected? Run the program a few times with a variety of input values.
- | The result will be left-justified. |
+ | Numerical results will always include a sign. |
space | Numerical results will include a leading space for positive values. |
0 | The result will be zero-padded. |
, | The result will include grouping separators, 12,345. |
( | The result will enclose negative numbers is parenthesis. |
Upload your completed program to Canvas.