How to include variables within strings?
You can incorporate variables into Java strings using concatenation with the +
operator:
Or better yet, format strings using String.format()
to replace placeholders:
For those utilizing JDK 15 and later, you can opt for the formatted()
method for a more seamless syntax:
Advanced variable inclusion techniques
We've shown basic concatenation; let's explore advanced techniques like String.format()
, MessageFormat
, and libraries like Apache Commons Text.
The charm of String.format()
String.format()
offers an efficient and tidy approach when dealing with multiple variables or complex layouts. It is powered by java.util.Formatter
, allowing for advanced formatting options:
This syntax comes in handy when creating tabular displays since it left-aligns the username to 10 characters and pads the user ID with zeros up to 5 digits.
Localization using MessageFormat
For applications needing internationalization, java.text.MessageFormat
is the key. It enables the use of indexed placeholders:
Use of mighty libraries
The Apache Commons Text library provides StringSubstitutor
, which offers recursive variable replacement for a more dynamic approach:
To use StringSubstitutor
, you'll need to include the Maven dependency for Apache Commons Text:
String::formatted() docking at Java 15+
Java 15 brought us String::formatted()
, simplifying things even further and allowing a more direct way to include variables:
This way, you'll find the code eloquent and crisp, easy on the eye.
Was this article helpful?