Java
Programming
String Formatting
Coding Tutorial
Software Development

How to format strings in Java

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Java offers several ways to format strings, and the best one depends on what you are building. For most code, String.format or printf is enough, while MessageFormat is better when the string is really a user-facing message template rather than just formatted output.

String.format For General Formatting

String.format is the standard choice when you want a formatted string back.

java
1public class Main {
2    public static void main(String[] args) {
3        String name = "Ava";
4        int age = 30;
5
6        String text = String.format("Name: %s, age: %d", name, age);
7        System.out.println(text);
8    }
9}

This works much like C-style format strings. %s formats a string and %d formats an integer.

This is a good default when:

  • you need alignment or numeric formatting
  • you want one clear template string
  • you want the result as a String

printf When You Are Printing Directly

If you are formatting only to print to a stream, printf can be more direct.

java
1public class Main {
2    public static void main(String[] args) {
3        double price = 12.5;
4        System.out.printf("Price: $%.2f%n", price);
5    }
6}

The format specifiers are the same idea as String.format, but the output goes directly to the stream instead of returning a string.

Common Format Specifiers

A few specifiers cover most day-to-day work:

  • '%s for strings'
  • '%d for integers'
  • '%f for floating-point values'
  • '%.2f for floating-point values with two decimals'
  • '%n for a platform-correct newline'
  • '%% for a literal percent sign'

Example:

java
1public class Main {
2    public static void main(String[] args) {
3        String report = String.format("User: %s, score: %d, success: %.1f%%",
4                "Noah", 87, 91.5);
5        System.out.println(report);
6    }
7}

Width And Alignment

Formatting becomes especially useful when you need aligned output.

java
1public class Main {
2    public static void main(String[] args) {
3        System.out.printf("|%-10s|%5d|%8.2f|%n", "apple", 7, 1.25);
4        System.out.printf("|%-10s|%5d|%8.2f|%n", "banana", 12, 0.75);
5    }
6}

%-10s left-aligns a string in a width of 10, and %5d right-aligns an integer in a width of 5.

MessageFormat For Template-Like Messages

MessageFormat is a better fit when the string is more like a user-facing message template, especially when localization matters.

java
1import java.text.MessageFormat;
2
3public class Main {
4    public static void main(String[] args) {
5        String pattern = "User {0} uploaded {1} files.";
6        String text = MessageFormat.format(pattern, "Ava", 3);
7        System.out.println(text);
8    }
9}

This style is easier to externalize for translated or configurable messages than %-based formatting.

String Concatenation Still Has A Place

Not every formatted string needs a formatting API.

java
String message = "Hello, " + name;

For very simple cases, concatenation or interpolation-like building is often clearer than String.format. Do not use formatting syntax when plain string assembly is easier to read.

Formatting Dates And Numbers

For serious locale-aware formatting of numbers, currency, or dates, dedicated classes are often better than generic string formatting.

For example, numeric formatting can use NumberFormat:

java
1import java.text.NumberFormat;
2import java.util.Locale;
3
4public class Main {
5    public static void main(String[] args) {
6        NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US);
7        System.out.println(currency.format(1234.56));
8    }
9}

This is more appropriate than hardcoding currency symbols into String.format when localization matters.

Common Pitfalls

The most common mistake is using the wrong format specifier, such as %d for a string or %s when numeric formatting was actually needed.

Another mistake is forgetting that %n is preferred over \n in format strings when you want platform-correct newlines.

Developers also overuse String.format for trivial concatenation, which can make simple code harder to read.

Finally, do not use %-style formatting as a substitute for proper locale-aware date, number, and currency formatting when the output is user-facing.

Summary

  • Use String.format when you want a formatted String result.
  • Use printf when you want to write formatted output directly.
  • Learn the common specifiers such as %s, %d, %.2f, %n, and %%.
  • Use MessageFormat for message-template style formatting, especially with localization.
  • Prefer dedicated date and number formatters when locale-sensitive output matters.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.