What is a Format Specifier?
A format specifier is a special symbol used inside System.out.printf() or String.format() to control how values are printed.
It starts with a % sign, followed by a character or number that tells Java what type of value to print and how to format it.
Example
System.out.printf("My age is %d and my name is %s", 20, "Saraswathi");
output
My age is 20 and my name is Saraswathi
Here:
%d → integer (age)
%s → string (name)
Common Format Specifiers
%d→ for all integer types (byte,short,int,long)%f→ for floating-point numbers (float,double)%c→ for characters%b→ for booleans%s→ for strings
Special Characters (Escape Sequences)
\n-> moves to next line\t-> adds horizontal space%n-> newline
Formatting Options
You can control width, alignment, and precision:
%5d Print integer in a field of width 5 (right-aligned) ' 25'
%-5d Print integer in width 5 (left-aligned) '25 '
%05d Print integer padded with zeros '00025'
%.2f Print float with 2 digits after decimal 3.14
%10.2f Total width = 10, 2 digits after decimal ' 3.14'
example
public class FormatDemo {
public static void main(String[] args) {
int age = 22;
float mark = 95.678f;
char grade = 'A';
String name = "Saraswathi";
boolean pass = true;
System.out.printf("Name: %-10s Age: %2d Marks: %.2f Grade: %c Pass: %b%n",
name, age, mark, grade, pass);
}
}
output
Name: Saraswathi Age: 22 Marks: 95.68 Grade: A Pass: true
Top comments (0)