A neatly aligned bill
Text columns use - to left-align; number columns right-align so the decimal points line up. 10 + 1 + 5 + 1 + 9 = 26 characters per row.
System.out.print writes text, println writes text and ends the line, and printf fills a template such as "%-10s %6.2f%n" with values, controlling width, alignment, decimal places and signs. String.format and formatted do the same but give you the String instead of printing it.
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 7 from 1 to 5, with the numbers right-aligned in width 3, like 7 x 1 = 7.
Given double celsius = 36.6;, print the temperature in Fahrenheit (c * 9 / 5 + 32) with exactly one decimal place and a degree label, e.g. 36.6 C = 97.9 F.
Use String.format to build an invoice id INV-2026-00042 from the year 2026 and the number 42, store it in a variable, then print it and its length.
Explain it without notes
What is the difference between print, println and printf?
Explain each part of the specifier %-12.3f, and what it prints for Math.PI.
Why doesn't the compiler catch printf("%d", 2.5), and what happens at run time?
Why should machine-readable output pass an explicit Locale to String.format?
Expected output
Item Qty Price
Pen 3 10.50
Notebook 12 45.00
Bag 1 899.99
--------------------------
Total 1471.49