String.format
- Java course
- Beginner
- Lesson 34/116
- 4 min
Learn formatting with String.format().
String.format
String.format fills a template with values. %s for String, %d for integer, %.2f for decimal.
String name = "Alex";
int age = 28;
String result = String.format("Hello %s, age %d", name, age);
// "Hello Alex, age 28"%.2f rounds the decimal to two digits: String.format("Price: %.2f", 9.999) → "Price: 10.00".
The template must match the number of variables; otherwise an exception is thrown.
Practice Use String.format
Write a Main class with a main method. Assign "Alex" to String name and 28 to int age. Assign String.format("Hello %s, age %d", name, age) to String result. Print result with println.
Sample solution
public class Main {
public static void main(String[] args) {
String name = "Alex";
int age = 28;
String result = String.format("Hello %s, age %d", name, age);
System.out.println(result);
}
}Expected output
Hello Alex, age 28
Common placeholders
The most common placeholders:
%s: String%d: integer (int, long)%f: decimal (double, float)%.2f: two decimal digits%n: platform-correct newline%b: boolean
For width use %5d (5 chars right-aligned), %-5d (left-aligned). This is useful for tabular output.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the placeholders
| Term | Meaning |
|---|---|
%s |
String |
%d |
Integer |
%.2f |
Decimal |
%n |
Newline |
2 Complete the placeholder
String s = String.format("Age: ____", 28);
String s = String.format("Age: %d", 28);
Explanation: %d is the integer placeholder.
3 Which is the placeholder for decimals?
- %f Correct answer
- %d
- %s
- %n
Explanation: %f is the decimal placeholder.