← Back to Core Java Course | Chapter 2: Input & Output | Lesson 5 of 6

Java printf & format

Basic printf Syntax

printf() takes a format string containing placeholders like %s (string) and %d (integer), then substitutes your arguments into those placeholders in order when it prints.

Example: Basic printf Syntax

java
public class Main {
	public static void main(String[] args) {
		System.out.printf("%s is %d years old%n", "Alice", 30);
	}
}

Formatting Decimals

The %f specifier prints floating-point numbers, and adding a precision like %.2f rounds and displays exactly two digits after the decimal point -- handy for formatting currency or measurements consistently.

Example: Formatting Decimals

java
public class Main {
	public static void main(String[] args) {
		System.out.printf("%.2f%n", 19.999); // rounds to exactly 2 decimal places
	}
}

Width and Alignment

Putting a number before the conversion character, like %10d, pads the output to at least that many characters wide; prefixing that width with a minus sign, %-10d, left-aligns it instead of the default right-alignment.

Example: Width and Alignment

java
public class Main {
	public static void main(String[] args) {
		System.out.printf("[%10d]%n", 42);  // right-aligned, padded to width 10
		System.out.printf("[%-10d]%n", 42); // left-aligned instead
	}
}

Printing Multiple Variables

Extra arguments beyond the first are matched to placeholders left to right, so printf("%s is %d", name, age) requires exactly one String and one int argument in that order or you'll get a runtime format exception.

Example: Printing Multiple Variables

java
public class Main {
	public static void main(String[] args) {
		String name = "Bob";
		int age = 25;
		System.out.printf("%s is %d%n", name, age); // matched left to right
	}
}

System.out.format()

System.out.format() is a plain alias for printf() defined on PrintStream -- both accept identical format syntax and arguments, so which one you call is purely a matter of personal style.

Example: System.out.format()

java
public class Main {
	public static void main(String[] args) {
		System.out.format("%s scored %d%n", "Sam", 95); // format() is an alias for printf()
	}
}
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.