AI Hints
Home›Java Tutorial›Comparing Strings, Escapes and Text Blocks, String.format
Java · Lesson 24 of 120

String.format

Tidy output.

⏱ 2 min read▶ Video at 31:38🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Joining lots of pieces with plus gets messy. String dot format lets you write a template, with gaps, and fills them in.

  • Plus gets messy
  • A template with gaps
  • Filled in for you

Format codes

Percent s is a gap for any value, usually a string. Percent d is a gap for a whole number. Percent dot two f shows a decimal with two places. And percent n is a new line.

keyvalue
%sa string
%da whole number
%.2fa decimal, 2 places
%na new line

Formatting in action

String dot format fills each gap, in order. Printf formats and prints, in one step. A width, like eight, right aligns the text, in eight characters. A minus sign left aligns it instead. A zero pads numbers with zeros. And formatted is a shorter way to do the same thing. Run it. The price shows four point five zero. And the brackets show the padding clearly.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String name = "Sam";
        int age = 30;
        double price = 4.5;
        System.out.println(String.format("%s is %d years old", name, age));
        System.out.printf("Price: %.2f%n", price);
        System.out.printf("[%8s]%n", name);
        System.out.printf("[%-8s]%n", name);
        System.out.printf("[%5d] [%05d]%n", age, age);
        System.out.println("Ready: %s and %s".formatted("tea", "cake"));
    }
}
Output
Sam is 30 years old
Price: 4.50
[     Sam]
[Sam     ]
[   30] [00030]
Ready: tea and cake

Summary

Format fills gaps in a template. Percent s for text, percent d for whole numbers, and percent dot two f for prices. Next, reading input from the keyboard.

Key takeaways
  • String.format
  • printf
  • %s %d %.2f %n
Next up: Reading Input with Scanner — talk to your program