← Back to Core Java Course | Chapter 6: Strings | Lesson 4 of 5

Java String Formatting

Basic String.format

String.format() builds a formatted string using placeholders like %s for text, %d for integers, and %f for decimals, then hands you back the finished String to store, log, or pass along — it doesn't print anything itself.

Example: Basic String.format

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

Printing directly with printf

System.out.printf() uses the exact same format-specifier syntax as String.format(), but writes the result straight to the console instead of returning a String, which saves a step when you just want to display formatted output immediately.

Example: Printing directly with printf

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

Formatting Decimal Places

The %f specifier formats floating-point values, and you can control precision with a modifier like %.2f to show exactly two decimal places — without it, Java defaults to six decimal places, which is rarely what you want for things like currency.

Example: Formatting Decimal Places

java
public class Main {
	public static void main(String[] args) {
		double price = 9.5;
		System.out.printf("%.2f%n", price);
	}
}

Integer Padding and Zero Fill

Flags like %5d (minimum width, right-padded with spaces) or %05d (zero-padded) let you align columns of numbers so they print neatly, which matters when formatting tabular console output like a report or a scoreboard.

Example: Integer Padding and Zero Fill

java
public class Main {
	public static void main(String[] args) {
		System.out.printf("%5d%n", 42);
		System.out.printf("%05d%n", 42);
	}
}

Formatting Date & Time Elements

The %t specifier family formats date and time values, combined with a conversion character such as Y for a four-digit year or m for a two-digit month — you need one %t group per component you want to display, since each only extracts a single piece of the date.

Example: Formatting Date & Time Elements

java
import java.util.Calendar;
public class Main {
	public static void main(String[] args) {
		Calendar cal = Calendar.getInstance();
		System.out.printf("%tY-%tm%n", cal, cal);
	}
}
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 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.