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

Java String.format()

Basic String Formatting

String.format() builds and returns a formatted String value using the same %s/%d/%f placeholder syntax as printf(), but instead of writing to the console it hands you the result to store, log, or pass along.

Example: Basic String Formatting

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

Numeric Formatting

Flags like %,d insert thousands separators (1,000,000) and %.2f controls decimal precision, letting you turn a raw double like 1234.5 into a properly formatted "1,234.50" for display.

Example: Numeric Formatting

java
public class Main {
	public static void main(String[] args) {
		String result = String.format("%,.2f", 1234.5); // "1,234.50"
		System.out.println(result);
	}
}

Locale-Specific Formatting

Passing a Locale (like Locale.GERMANY) as the very first argument tells String.format() to use that region's conventions -- for example, swapping the decimal comma and thousands-period used in much of Europe.

Example: Locale-Specific Formatting

java
import java.util.Locale;
public class Main {
	public static void main(String[] args) {
		String result = String.format(Locale.GERMANY, "%,.2f", 1234.5); // "1.234,50"
		System.out.println(result);
	}
}

Padding and Alignment

Padding a string to a fixed width with %10s (or %-10s to left-align) is what makes columns of text -- like a receipt or a report -- line up visually even when the values are different lengths.

Example: Padding and Alignment

java
public class Main {
	public static void main(String[] args) {
		System.out.println(String.format("[%10s]", "hi"));  // right-aligned, width 10
		System.out.println(String.format("[%-10s]", "hi")); // left-aligned
	}
}

Reusing Arguments

Argument index syntax like %1$s lets you reference the same argument more than once, or print your arguments in a different order than you passed them, without duplicating them in the call.

Example: Reusing Arguments

java
public class Main {
	public static void main(String[] args) {
		String result = String.format("%1$s is %1$s again", "Java"); // reuses argument 1 twice
		System.out.println(result);
	}
}
🔒

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.