String Formatting (String.format, printf) in Java
String.format and System.out.printf both build formatted text from a template string containing placeholders — %s for a string, %d for an integer, %f for a floating-point number, and several more — substituting each placeholder with the corresponding argument in order. The difference between the two is just where the result goes: String.format returns the formatted text as a String to store or pass around, while printf writes it straight to standard output.
Placeholders support extra formatting details inside them — %.2f rounds a decimal to two places, %5d pads a number to a minimum width of 5 characters, and %-10s left-aligns a string inside a 10-character field. That's precise alignment and rounding that plain string concatenation can't do cleanly.
The basic placeholders
%s for a String, %d for an integer, %f for a floating-point number, each replaced by the matching argument in order.
String.format vs printf
String.format returns the formatted text as a String; printf writes that same formatted text directly to standard output.
Controlling decimal places
%.2f rounds a floating-point value to exactly two digits after the decimal point.
Controlling width and alignment
%5d pads a number to at least 5 characters wide, and a minus sign like %-10s left-aligns instead of the default right-alignment.
Multiple placeholders, one call
A single format string can contain several placeholders, filled in order by however many arguments follow it.
public class FormatDemo { public static void main(String[] args) { String message = String.format("Name: %-10s Score: %6.2f", "Ada", 95.5); System.out.println(message); System.out.printf("Total: %d items%n", 3); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.