1. The problem with manual concatenation
If you need to output one or two variables, the + operator is indeed convenient. But when there’s a lot of data, concatenation quickly turns into chaos, especially if number formatting is required (for example, 2 decimal places) or line breaks.
String name = "Oleg";
int age = 25;
double balance = 12345.67;
System.out.println("Name: " + name + ", age: " + age + ", balance: " + balance + " euros.");
Trying to “tweak” formatting inside concatenation only worsens readability:
System.out.println("Name: " + name + ", age: " + age + ", balance: " + String.format("%.2f", balance) + " euros.");
Conclusion: simple concatenation is fine for small things, but for complex messages you need a more powerful tool — String.format().
2. String.format — formatting strings like a pro
The String.format() method lets you create a string from a template and substitute values at specified positions.
General form:
String result = String.format("Template", values);
- %s — string
- %d — integer
- %f — floating-point number
- %n — line break (cross-platform)
String name = "Oleg";
int age = 25;
double balance = 12345.6789;
String info = String.format("Name: %s, age: %d, balance: %.2f euros.", name, age, balance);
System.out.println(info);
// Will print: Name: Oleg, age: 25, balance: 12345.68 euros.
String result = String.format("Name: %s, age: %d, balance: %.2f euros", name, age, balance);
// %s — string, %d — integer, %.2f — a number with 2 digits after the decimal point
Formatting numbers and strings
Floating-point numbers with fixed precision:
double price = 99.999;
System.out.println(String.format("Price: %.2f euros.", price)); // Price: 100.00 euros.
Field width and alignment:
int n = 7;
System.out.println(String.format("Number: [%5d]", n)); // Number: [ 7]
System.out.println(String.format("Number: [%-5d]", n)); // Number: [7 ]
[5d] — field width 5, right-aligned by default;
[-5d] — field width 5, left-aligned.
Strings with alignment:
String text = "Java";
System.out.println(String.format("[%10s]", text)); // [ Java]
System.out.println(String.format("[%-10s]", text)); // [Java ]
Percentages:
double percent = 0.125;
System.out.println(String.format("Done: %.1f%%", percent * 100)); // Done: 12.5%
To print a percent sign, use %%.
Date formatting (briefly)
import java.util.Date;
Date now = new Date();
System.out.println(String.format("Today: %tD", now)); // Today: 06/18/24
System.out.println(String.format("Time: %tT", now)); // Time: 15:42:07
Localization and separators
By default, the system locale is used. To specify your own (for example, a comma as the decimal separator), pass a locale — for example, Locale.FRANCE.
import java.util.Locale;
double price = 1234.56;
System.out.println(String.format(Locale.FRANCE, "%.2f", price)); // 1234,56
Practical examples
Example 1: Short report
String name = "Anna";
int tasks = 5;
double hours = 12.3456;
String report = String.format(
"Employee: %s%nTasks completed: %d%nHours spent: %.1f",
name, tasks, hours
);
System.out.println(report);
/* Output:
Employee: Anna
Tasks completed: 5
Hours spent: 12.3
*/
Example 2: Table with alignment
String header = String.format("%-10s | %5s | %8s", "Name", "Score", "Time");
String row1 = String.format("%-10s | %5d | %8.2f", "Oleg", 95, 10.5);
String row2 = String.format("%-10s | %5d | %8.2f", "Anna", 100, 9.75);
System.out.println(header);
System.out.println(row1);
System.out.println(row2);
/* Output:
Name | Score | Time
Oleg | 95 | 10.50
Anna | 100 | 9.75
*/
Example 3: Mixed text
int apples = 12;
int pears = 8;
System.out.println(String.format("I have %d apples and %d pears.", apples, pears));
3. Practice: string formatting in our application
Let’s add formatting to a console application: balance should always have two digits after the decimal point, and line breaks — via %n.
Scanner console = new Scanner(System.in);
System.out.print("Enter name: ");
String name = console.nextLine();
System.out.print("Enter age: ");
int age = console.nextInt();
System.out.print("Enter balance: ");
double balance = console.nextDouble();
// Formatted output
String info = String.format("Name: %s, age: %d, balance: %.2f euros.", name, age, balance);
System.out.println(info);
Try:
- Enter different values and verify that the balance is always printed with two decimal places (%.2f).
- Modify the template to add line breaks using %n.
4. Common mistakes when formatting strings
Mistake No. 1: Type and specifier mismatch.
Do not pass a string to %d or a number to %s.
String.format("Age: %d", "twenty"); // Error: expected a number, passed a string
Mistake No. 2: Arguments in the wrong order.
The pattern is %s %d, but you pass a number first and then a string — you’ll get an error or incorrect output.
Mistake No. 3: Ignoring the locale.
You expected a comma as the decimal separator but see a dot — set the desired locale explicitly via the first parameter to String.format(...).
Mistake No. 4: Unescaped percent sign.
To print the % character, use %%; otherwise formatting will fail with an error.
GO TO FULL VERSION