Java printf & format
In this page:
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
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 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
public class Main {
public static void main(String[] args) {
System.out.printf("%.2f%n", 19.999); // rounds to exactly 2 decimal places
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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()
public class Main {
public static void main(String[] args) {
System.out.format("%s scored %d%n", "Sam", 95); // format() is an alias for printf()
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: