How to format strings in Java
Here's the quick way to format strings in Java using String.format()
:
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!
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:
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.
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:
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):
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).
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.
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!
Object-Oriented with Cactoos
For those with an object-oriented approach or just looking to experiment, try Cactoos for a unique string formatting adventure.
Was this article helpful?