Lesson 3 of 614 minModule progress 0%

Module 10: Strings, Files, and Everyday Core APIs

Formatting Output with printf and format

Format numbers, text, and aligned output so your programs look cleaner and easier to read.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Use placeholders for clearer output formatting
  • Format numbers and labels more predictably
  • Keep display logic separate from raw data values

Formatting improves readability: Instead of stitching raw values into messy text, placeholders keep output shape predictable.

String.format() is useful for reports, receipts, and aligned output: You can control decimal places, text placement, and spacing.

This matters beyond the console: Good formatting habits carry into logs, exports, and generated emails.

Think in two steps: first compute the data, then format it for display.

Runnable examples

Format money with two decimals

double total = 19.5;
String line = String.format("Total: $%.2f", total);
System.out.println(line);

Expected output

Total: $19.50

Mini exercise

Format a product name and price using `String.format()` so the price always shows two decimal places.

Summary

  • Formatting makes output easier to scan.
  • `String.format()` is useful for reports and receipts.
  • Compute values first, then format them for display.

Next step

Next, search and validate text patterns with regular expressions.

Sources used

Advertisement

Lesson check

What is a common reason to use `String.format()`?

Next lesson →