How to Format Strings Using String.format()

In Java, the String.format() method is a convenient way to create formatted strings using placeholders. It allows you to include values such as numbers or strings at specific positions in a string by using format specifiers. Here’s how you can use it:

Syntax

String.format(String format, Object... args)
  • format: The format string with placeholders.
  • args: The arguments to replace the placeholders.

Common Format Specifiers

  • %s: String.
  • %d: Decimal integer.
  • %f: Floating-point number.
  • %c: Character.
  • %%: Literal % character.

You can combine these with width, precision, alignment, and other formatting options.


Examples

1. String Formatting

String name = "John";
int age = 30;
String formattedString = String.format("My name is %s and I am %d years old.", name, age);
System.out.println(formattedString);
// Output: My name is John and I am 30 years old.

2. Formatting Numbers

double price = 123.456789;
String formattedPrice = String.format("The price is %.2f.", price);
System.out.println(formattedPrice);
// Output: The price is 123.46.
  • %.2f: Limits the floating-point value to 2 decimal places.

3. Padding and Alignment

  • Right-aligned text:
String formattedString = String.format("%10s", "Java");
System.out.println(formattedString);
// Output: "      Java" (padded with spaces to the left, 10 characters in total)
  • Left-aligned text:
String formattedString = String.format("%-10s", "Java");
System.out.println(formattedString);
// Output: "Java      " (padded with spaces to the right, 10 characters in total)

4. Adding Leading Zeros

int number = 42;
String formattedNumber = String.format("%05d", number);
System.out.println(formattedNumber);
// Output: 00042

5. Formatting Multiple Values

String result = String.format("%s scored %d out of %d in the exam.", "Alice", 90, 100);
System.out.println(result);
// Output: Alice scored 90 out of 100 in the exam.

6. Escaping %

To include a literal % in the string, use %%.

String formattedString = String.format("Progress: %.2f%%", 85.123);
System.out.println(formattedString);
// Output: Progress: 85.12%

Notes

  1. Null Values: If a value in args is null, %s outputs the string "null".
  2. Exceptions: Make sure the placeholders match the number and type of arguments; otherwise, it may throw an exception (e.g., IllegalFormatException).

Formatted strings are especially useful when generating user-friendly messages or handling precise output formatting, such as in reporting systems or logs.