Java Format String Tutorial

Java provides a robust way to format strings using the String.format() method, printf(), and the Formatter class. String formatting in Java is crucial for creating well-structured outputs, logs, and user-friendly messages. This tutorial will guide you through Java’s format string capabilities, including placeholders, formatting flags, and best practices.

1. Understanding String.format()

The String.format() method in Java is used to create formatted strings. It follows a specific syntax similar to C’s printf().

Syntax:

String formattedString = String.format(format, arguments);
  • format: A string containing format specifiers.
  • arguments: Values that will replace the format specifiers.

Example:

String name = "Alice";
int age = 25;
String formattedString = String.format("Name: %s, Age: %d", name, age);
System.out.println(formattedString);

Output:

Name: Alice, Age: 25

2. Format Specifiers

Format specifiers define how values should be formatted within a string. The general syntax is:

%[flags][width][.precision]conversion-character

Common Format Specifiers:

Specifiers

3. Formatting Flags

Flags modify the behavior of format specifiers.

Common Flags:

Flags

Example Usage:

System.out.println(String.format("%-10s | %+5d | %010d", "Java", 42, 42));

Output:

Java       |   +42 | 0000000042

4. Precision and Width

Width

Width defines the minimum number of characters to be printed.

Example:

System.out.println(String.format("%10s", "Java"));

Output:

      Java

(The output is right-aligned with 10 spaces.)

Precision

Precision controls the number of digits after the decimal point for floating-point numbers.

Example:

System.out.println(String.format("%.2f", 3.14159));

Output:

3.14

5. Using printf() For Direct Formatting

Instead of String.format(), Java allows formatted output directly to the console using System.out.printf().

Example:

System.out.printf("Hello %s, you are %d years old.\n", "Bob", 30);

Output:

Hello Bob, you are 30 years old.

6. Using the Formatter Class

The Formatter class provides advanced formatting capabilities.

Example:

Formatter formatter = new Formatter();
formatter.format("The price is: $%.2f", 19.99);
System.out.println(formatter);
formatter.close();

Output:

The price is: $19.99

7. Formatting Dates and Times

Java also allows formatting of dates and times using String.format() and DateTimeFormatter (Java 8+).

Example with String.format():

import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Date date = new Date();
        String formattedDate = String.format("Today is %tA, %<tB %<td, %<tY", date);
        System.out.println(formattedDate);
    }
}

Output:

Today is Monday, March 17, 2025

Note: %tA (day), %tB (month), %td (date), %tY (year).

Example with DateTimeFormatter (Java 8+):

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE, MMMM dd, yyyy HH:mm:ss");
        System.out.println("Current Time: " + now.format(formatter));
    }
}

8. Locale-Sensitive Formatting

To format numbers and dates based on different locales:

import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        double price = 1234.56;
        System.out.println(String.format(Locale.GERMANY, "%,.2f", price)); // German format
        System.out.println(String.format(Locale.US, "%,.2f", price)); // US format
    }
}

Output:

1.234,56
1,234.56

9. Escaping Percent Symbol (%%)

If you need to print a % symbol:

System.out.println(String.format("Discount: %d%%", 50));

Output:

Discount: 50%

10. Best Practices for String Formatting in Java

Best Practices

Conclusion

Java provides flexible and powerful formatting options through String.format()printf(), and Formatter. Mastering these formatting techniques allows developers to produce readable and well-structured output, essential for UI messages, logging, and data presentation.

This article was originally published on Medium.

Leave a Comment

Your email address will not be published. Required fields are marked *