Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to including variables within strings? [duplicate]

People also ask

How do you add a variable to a string in Java?

Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.


You can always use String.format(....). i.e.,

String string = String.format("A String %s %2d", aStringVar, anIntVar);

I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.


This is called string interpolation; it doesn't exist as such in Java.

One approach is to use String.format:

String string = String.format("A string %s", aVariable);

Another approach is to use a templating library such as Velocity or FreeMarker.


Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,

String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);

results in string containing the following:

A string of ponies.

More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.


Since Java 15, you can use a non-static string method called String::formatted(Object... args)

Example:

String foo = "foo";
String bar = "bar";

String str = "First %s, then %s".formatted(foo, bar);     

Output:

"First foo, then bar"


Apache Commons StringSubstitutor can be used.

import org.apache.commons.text.StringSubstitutor;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."

This class supports providing default values for variables.

String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."

To use recursive variable replacement, call setEnableSubstitutionInVariables(true);.

Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"