Command Palette

Search for a command to run...

Back to the lesson: Topic 6.6 — String Formatting
Core Java · Example 2 of 3

A neat table with printf

%-12.6s left-aligns in 12 characters but keeps at most 6. printf is Java 5; the divider uses String.repeat from Java 11.

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.

01

Print a multiplication table for 1 to 4 where every number is right-aligned in a 4-character column.

02

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.

03

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

01

Describe the full syntax of a format specifier and give an example using every part.

02

What is the difference between width and precision for %s and %f?

03

Why should you pass a Locale to String.format, and which one?

04

How does %.2f round, and how does that differ from DecimalFormat?

05

Which exceptions can formatting throw, and when do you find out about them?

A neat table with printf
Sign in to run this example in your browser.

Expected output

Item          Qty    Amount
---------------------------
tea             2     40.00
samosa          3     46.50
paneer tikka    1    180.00
Total                266.50
a-very          1      1.00