Java format Specifiers with printf
Java format Specifiers with printf
Java provides powerful formatting capabilities through the printf() method, which allows precise control
over how strings, numbers, and other data types are displayed. Formatting is especially useful for structured
output, reports, and aligning data properly.
Basic Syntax
System.out.printf(format_string, values);
Example:
Output:
Example:
String s = "Java";
System.out.printf("'%15s'%n", s); // Right-justified
System.out.printf("'%-15s'%n", s); // Left-justified
Output:
' Java'
'Java '
2. Integer Formatting
Example:
int num = 7;
System.out.printf("'%5d'%n", num); // Right-justified
System.out.printf("'%-5d'%n", num); // Left-justified
System.out.printf("'%03d'%n", num); // Leading zeros
Output:
' 7'
'7 '
'007'
3. Floating-Point Formatting
• %f → Decimal number (Example: 3.14 → 3.140000)
• %.2f → Decimal with 2 places (Example: 3.1415 → 3.14)
• %10.2f → Right-justified decimal with 2 places (Example: 3.14 → " 3.14")
• %-10.2f → Left-justified decimal with 2 places (Example: 3.14 → "3.14 ")
• %e → Scientific notation (Example: 1234.56 → 1.234560e+03)
Example:
double pi = 3.141592;
System.out.printf("%.2f%n", pi); // 2 decimal places
System.out.printf("%10.2f%n", pi); // Right-justified
System.out.printf("%-10.2f%n", pi); // Left-justified
System.out.printf("%e%n", pi); // Scientific notation
Output:
3.14
3.14
3.14
3.141592e+00
4. Boolean Formatting
Example:
System.out.printf("%b%n", true);
System.out.printf("%b%n", false);
Output:
true
false
Example:
Output:
Hex (lowercase): ff
Hex (uppercase): FF
Octal: 377
Binary: 11111111
Java’s printf() doesn't directly support date formatting, but you can use Java’s java.time API.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
Output (Example):
Output: