Command Palette

Search for a command to run...

Back to the lesson: Topic 1.12 — Printing and Formatting Output
Core Java · Example 4 of 4 Java 15+

String.format, formatted and locales

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.

01

Print a multiplication table for 7 from 1 to 5, with the numbers right-aligned in width 3, like 7 x 1 = 7.

02

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.

03

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

01

What is the difference between print, println and printf?

02

Explain each part of the specifier %-12.3f, and what it prints for Math.PI.

03

Why doesn't the compiler catch printf("%d", 2.5), and what happens at run time?

04

Why should machine-readable output pass an explicit Locale to String.format?

String.format, formatted and locales Java 15+
Sign in to run this example in your browser.

Expected output

Ravi is 12 years old
Order #00042
US:      1,428,627,663
Germany: 1.428.627.663
US:      1,234,567.89
Germany: 1.234.567,89