Shiklo Programming
EN
  • English
  • Español
  • Português
  • Deutsch
  • Français
  • 日本語
  • हिन्दी

Java String Formatting

Joining strings with + works, but when a line mixes text and numbers, it soon becomes hard to read and the numbers do not line up. Formatting solves this: you write a template with placeholders, and Java fills them with values in a fixed way. You met printf briefly in the Output topic.

Placeholders

PlaceholderForExample result
%dwhole numbers42
%fdecimal numbers3.141593
%.2fdecimal number, 2 digits after the point3.14
%stext (or anything)Asha
%cone characterA
%ba booleantrue
%na new line
%%a percent sign%
public class Main {
    public static void main(String[] args) {
        String name = "Meera";
        int items = 3;
        double total = 1249.5;
        System.out.printf("%s bought %d items for %.2f rupees.%n", name, items, total);
        System.out.printf("Discount: 10%%%n");
    }
}
Output
Meera bought 3 items for 1249.50 rupees.
Discount: 10%

The values are used in order: the first placeholder takes the first value, and so on.

String.format and formatted

printf prints at once. String.format builds the same text and returns it, so you can store it or use it later. formatted does the same, called on the template itself:

public class Main {
    public static void main(String[] args) {
        String line = String.format("%d x %d = %d", 6, 7, 6 * 7);
        System.out.println(line);
        String msg = "Hello, %s!".formatted("Ravi");
        System.out.println(msg);
    }
}
Output
6 x 7 = 42
Hello, Ravi!

Width and alignment

A number between % and the letter sets a minimum width. Text is pushed to the right; a minus sign pushes it to the left. A comma adds thousands separators. This makes neat tables:

public class Main {
    public static void main(String[] args) {
        System.out.printf("%-10s%8s%n", "Item", "Price");
        System.out.printf("%-10s%8.2f%n", "Pen", 15.0);
        System.out.printf("%-10s%8.2f%n", "Notebook", 120.5);
        System.out.printf("%,d%n", 1234567);
        System.out.printf("%05d%n", 42);
    }
}
Output
Item         Price
Pen          15.00
Notebook    120.50
1,234,567
00042

%-10s uses 10 places for the text, aligned left; %8.2f uses 8 places for the number, aligned right, with 2 decimals. %05d fills the width with zeros.

Text blocks

For text that spans several lines, Java has text blocks: three double quotes, a new line, the text, and three double quotes at the end. The indentation common to all lines is removed:

public class Main {
    public static void main(String[] args) {
        String card = """
            Name: %s
            Course: %s
            Grade: %c
            """.formatted("Kiran", "Java", 'A');
        System.out.print(card);
    }
}
Output
Name: Kiran
Course: Java
Grade: A

Text blocks are convenient for menus, messages and small reports. Combined with formatted, they work like a fill-in-the-blanks form.

Practice exercises

  1. Print Pi is about 3.14159 with printf, using Math.PI and 5 decimals.
  2. Print a three-row table of names and marks with the names aligned left and the marks aligned right.
  3. Build a two-line receipt with a text block and formatted.