Course contentsShow
← Java
Lesson 2019 of 2,87040. File I/O: Character StreamsFree lesson

printf and format: Formatted Output

Use printf and format methods with format specifiers to produce precisely formatted text output.

printf and format: Formatted Output

What you'll learn: How to produce precisely formatted text output using printf and format methods with format specifiers.

When you've used print and println, you get basic output—but sometimes you need more control. What if you want numbers aligned in columns, decimal places limited to two digits, or dates formatted consistently? That's where printf and format come in.

The Core Idea

PrintWriter provides two identical methods for formatted output: printf and format. They work exactly the same way—printf exists for programmers familiar with C, while format is more Java-idiomatic. Both accept a format string with placeholders called format specifiers, followed by values to insert at those positions.

Think of format specifiers as fill-in-the-blank templates: "The price is ____" becomes "The price is %.2f", where %.2f means "insert a floating-point number with 2 decimal places."

Common Format Specifiers

  • %d – integer (decimal)
  • %f – floating-point number
  • %.2f – floating-point with 2 decimal places
  • %s – string
  • %n – platform-specific newline

How It Works

PrintWriter writer = new PrintWriter("output.txt");

writer.printf("Name: %s, Age: %d%n", "Alice", 30);
writer.format("Price: $%.2f%n", 19.99);

writer.close();

This produces:

Name: Alice, Age: 30
Price: $19.99

The %s is replaced by "Alice", %d by 30, and %.2f by 19.99 formatted to two decimals.

Key Takeaway: Use printf or format with format specifiers like %d, %f, and %s to control exactly how text and numbers appear in your output, ensuring consistent formatting across your data.