Explain Codes LogoExplain Codes Logo

How to include variables within strings?

java
string-formatting
variable-inclusion
java-advanced-techniques
Alex KataevbyAlex Kataev·Sep 4, 2024
TLDR

You can incorporate variables into Java strings using concatenation with the + operator:

String info = "Name: " + name + ", Age: " + age;

Or better yet, format strings using String.format() to replace placeholders:

String info = String.format("Name: %s, Age: %d", name, age);

For those utilizing JDK 15 and later, you can opt for the formatted() method for a more seamless syntax:

String info = "Name: %s, Age: %d".formatted(name, age);

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:

// Displaying username and userId in style! Style points matter, right? String userDetails = String.format("User: %-10s | ID: %05d", userName, userId);

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:

// Who said you can't code and learn languages simultaneously? 🌍 MessageFormat.format("{0}, you have {1} new messages", userName, newMessages);

Use of mighty libraries

The Apache Commons Text library provides StringSubstitutor, which offers recursive variable replacement for a more dynamic approach:

Map<String, String> valuesMap = new HashMap<>(); valuesMap.put("user", userName); valuesMap.put("messageCount", String.valueOf(newMessages)); String templateString = "Hello ${user}, you have ${messageCount} new messages."; StringSubstitutor sub = new StringSubstitutor(valuesMap); // Brace yourselves messages are coming... String resolvedString = sub.replace(templateString);

To use StringSubstitutor, you'll need to include the Maven dependency for Apache Commons Text:

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.10.0</version> </dependency>

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:

Sha256Hash.digest("makeJavaBetterAgain", "Welcome, %s!".formatted(userName));

This way, you'll find the code eloquent and crisp, easy on the eye.