The specifiers you'll use every day
formatted() needs Java 15; everything else here works since Java 5.
String.format, printf and formatted build text from a template with placeholders like %s, %d and %.2f, giving you control over width, alignment, padding, decimals and grouping. Pass a Locale for numbers, because the decimal and thousands separators change by country.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Print a multiplication table for 1 to 4 where every number is right-aligned in a 4-character column.
Write static String bar(String label, int percent) that prints label left-aligned in 8 characters, then percent right-aligned in 3 characters followed by %, then that many # characters divided by 10. Print it for cpu 72 and memory 35.
Format the number of bytes 1536000 as a human-readable size with one decimal place: 1.5 MB (use 1024-based units and Locale.ROOT).
Explain it without notes
Describe the full syntax of a format specifier and give an example using every part.
What is the difference between width and precision for %s and %f?
Why should you pass a Locale to String.format, and which one?
How does %.2f round, and how does that differ from DecimalFormat?
Which exceptions can formatting throw, and when do you find out about them?
Expected output
Asha is 30 years old
price: 1234.57
grouped: 1,234.57
accounting: (1,234.57)
right [ Asha] left [Asha ] cut [As]
zero-pad [00042] sign [+42]
hex ff FF 0xff, octal 10
scientific 1.234568e+03, pi [ 3.142]
char J, booleans true false, percent 100%
second before first
echo and echo again
Ravi scored 91