๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Java String Formatting

String formatting shapes numbers and words into a fixed layout. Placeholders in a pattern mark where each value lands.

Two decimal places round a price

The pattern keeps two places after the point. The price rounds to 3.14.

public class Main {
  public static void main(String[] args) {
    double price = 3.14159;
    String text = String.format("%.2f", price);
    System.out.println(text);
  }
}

Numbers and words mix in one sentence

Each placeholder takes one value in order. The sentence reads as plain text.

public class Main {
  public static void main(String[] args) {
    String text = String.format("%s scored %d points", "Ana", 92);
    System.out.println(text);
  }
}

Width pads with leading spaces

Width five makes the number five characters wide. Three leading spaces fill the gap.

public class Main {
  public static void main(String[] args) {
    String text = String.format("[%5d]", 42);
    System.out.println(text);
  }
}

Zero padding fills with zeros

The zero flag swaps spaces for zeros. The number still fills five characters.

public class Main {
  public static void main(String[] args) {
    String text = String.format("[%05d]", 42);
    System.out.println(text);
  }
}

Example

public class Main {
  public static void main(String[] args) {
    System.out.printf("%s: %5d points%n", "Ana", 92);
    System.out.printf("%s: %5d points%n", "Ben", 7);
  }
}

Key points

  • String.format returns a shaped String without printing it.
  • A percent d placeholder takes an integer, and percent s takes a word.
  • A percent point two f placeholder rounds a decimal to two places.
  • A width in a placeholder pads a number with leading spaces.
  • A zero flag pads a number with leading zeros instead.
  • Printf prints the same shapes directly, and percent n ends its lines.

In this example, printf prints two score lines directly, and the width keeps both numbers in one column.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does String.format("[%5d]", 42) print?