0Pricing
Java Academy · Lesson

String.format

Build formatted strings.

Format Without Printing

printf sends text straight to the console. But sometimes you want the formatted text as a String to store, return, or reuse.

String.format does exactly that: same rules, but it returns a value instead of printing.

Your First String.format

String.format uses the same placeholders as printf. It builds a new string and hands it back to you.

Here the result is stored in msg and then printed.

public class Main {
    public static void main(String[] args) {
        String msg = String.format("Hello, %s!", "World");
        System.out.println(msg);
    }
}

All lessons in this course

  1. printf Basics
  2. Number and Decimal Formats
  3. String.format
  4. Aligning Tables
← Back to Java Academy