Explain Codes LogoExplain Codes Logo

How to format strings in Java

java
string-formatting
java-8
internationalization
Alex KataevbyAlex Kataev·Nov 11, 2024
TLDR

Here's the quick way to format strings in Java using String.format():

String name = "John"; int age = 25; String formatted = String.format("Name: %s, Age: %d", name, age);

Remember: Use %s for strings, and %d for integers, and pepper these placeholders in your text wherever you want to inject dynamic content.

Position and format variables with ease

Know your position: Ordered replacements

Positional parameters in formatted strings let you order your replacements as per your wish, just like your favorite coffee!

// Revolver Ocelot style format String formatted = String.format("%2$s is %1$d years old.", age, name);

Here, %2$s refers to the second argument (a string), and %1$d refers to the first argument (an integer).

Internationalization? MessageFormat is your friend

For localized or complex string formatting, the java.text.MessageFormat.format can be your secret weapon:

// Greetings in multiple languages! String pattern = "{0} is {1} years old."; String formatted = MessageFormat.format(pattern, name, age);

Here, indexed variables {0} and {1} are used for placing the arguments, facilitating better i18n support.

Fluent formatting with String#formatted

In Java 15, String#formatted gifts you with a more fluent string formatting style that looks as graceful as a ballet.

// Smooth as butter String formatted = "Name: %s, Age: %d".formatted(name, age);

Optimal String concatenation: Choose your weapon

Concatenation with StringBuilder

StringBuilder allows for efficient concatenation of multiple strings like the series of movies on your weekend binge-watch list:

// Building my Omelas StringBuilder sb = new StringBuilder(); sb.append("Name: ").append(name).append(", Age: ").append(age); String formatted = sb.toString();

It's a quick choice, but with many appends it could become the Da Vinci Code for readers.

Concatenation using '+'

Sometimes, it's better to KISS (Keep It Simple, Silly):

// Clarity over cleverness String formatted = "Name: " + name + ", Age: " + age;

Though not always the most efficient, it's clean and understandable by any fresh-out-of-college intern.

Elegant Varargs and Autoboxing in Java 1.5 and above

The modern way of going about formatting strings utilizes varargs and autoboxing, it's just as refreshing as a new Star Wars movie (not the prequels, ew).

// Modernism at its finest String formatted = MessageFormat.format("{0} is about {1} years old.", name, age);

Shout out to autoboxing for converting integers to Integers and varargs for the flexibility in argument numbers!

i18n plurals with MessageFormat

MessageFormat also provides a nifty solution for formatting plurals, so you don’t offend grammarians around the world.

// Because Grammar Nazis are everywhere String pattern = "{0} {0,choice,0#cars|1#car|1<cars}"; String formatted = MessageFormat.format(pattern, carCount);

Now you can differentiate between one car and multiple cars in a locale-aware manner.

Exploring the wildlands of string formatting

The charm of Apache Commons

Apache Commons gives you string formatting wonders not supported by default in JDK, like finding water in a desert!

// When JDK just doesn't cut it. String formatted = StringEscapeUtils.escapeJava("string to escape");

Object-Oriented with Cactoos

For those with an object-oriented approach or just looking to experiment, try Cactoos for a unique string formatting adventure.

// Hey! That's pretty neat. String formatted = new FormattedText("Name: %s", name).asString();