Command Palette

Search for a command to run...

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

print, println and a first printf

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?

print, println and a first printf
Sign in to run this example in your browser.

Expected output

Hello, world

42
3.0
A
66
Java
Asha scored 92 points