Java String Formatting
In this page:
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
public class Main {
public static void main(String[] args) {
String result = String.format("%s is %d years old", "Alice", 30);
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.printf("%s is %d years old%n", "Alice", 30);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
double price = 9.5;
System.out.printf("%.2f%n", price);
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.printf("%5d%n", 42);
System.out.printf("%05d%n", 42);
}
}
Login to try C/C++/Java/PHP code in the editor
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 5 topics to unlock
0/5 topics done
Complete these topics first: