String interpolation

String interpolation is a process of inserting values into a string template at run-time.
This can be useful when you need to insert values into a string that is being displayed to the user or when you need to construct a string from values that are stored in variables.

In this article, we will be discussing 5 different ways to achieve string interpolation in java with examples.

1. String.format()
Java String.format() is used to replace pre-defined format strings with values.
Thus, it creates a dynamic string without using string concatenation.
Besides, it also provides flexibility to format strings, integers, floating values with required decimal places, hexadecimal, octal values, currencies, allows to pad values with spaces or some other values etc. Example,

// Substitute a single value into a string template
String name = "John";
String msg = String.format("Hello, %s!", name);
System.out.println(msg);

// Substitute multiple values into a string template
int quantity = 10;
double price = 5.99;
msg = String.format("You have ordered %d items at " + 
                      $%.2f each.", quantity, price);
System.out.println(msg);

Output is

Hello John
You have ordered 10 items at $5.99 each.

2. MessageFormat
Java MessageFormat class is another method of String interpolation. Its format() method allows to replace placeholders enclosed between curly braces with values from variables. Example,

int quantity = 10; double price = 5.99; 
String msg = MessageFormat.format("You have ordered {0} items at " +
                    ${1} each.", quantity, price);
System.out.println(msg);

Output is

You have ordered 10 items at $5.99 each.

It allows you to provide an array instead of separate values. Array elements are replaced at corresponding placeholders.
This becomes very convenient when the number of values is more. Example,

int quantity = 10; double price = 5.99;
Object[] arr = {quantity, price};
String msg = MessageFormat.format("You have ordered {0} items at " +
                  "${1} each.", arr);

MessageFormat supports advanced formatting options where you can provide formatting style along with placeholders.
So, you can instruct MessageFormat to format an argument as a date, currency, time etc.
These options are provided within curly braces after index. Example,

String message = "At {0,time, long} on {0,date}," +
                 " {1} paid {2,number, currency} for {3}.";
Object[] arguments = {
  new java.util.Date(),
  "A B",
  4.259,
  "a piece of gum"
};
String result = MessageFormat.format(message, arguments);
System.out.println(result);
message = "At {0,time, full} on {0,date, medium}," +
          " {1} paid {2,number, currency} for {3}.";
result = MessageFormat.format(message, arguments);
System.out.println(result);
message = "At {0,time, medium} on {0,date}," +
          " {1} paid {2,number} for {3}.";
result = MessageFormat.format(message, arguments);
System.out.println(result);

Output is

At 5:08:32 pm IST on 18-Dec-2022, A B paid ₹4.26 for a piece of gum.
At 5:08:32 pm India Standard Time on 18-Dec-2022, A B paid ₹4.26 for a piece of gum.
At 5:08:32 pm on 18-Dec-2022, A B paid 4.259 for a piece of gum.

3. StringBuilder
Java StringBuilder class allows you to create mutable strings.
Mutable means that you can perform operations on string values without creating different string objects since string objects themselves are immutable.

StringBuilder provides an append() method which accepts values of different types and appends the supplied value to a string.
Thus, it allows to create interpolated string as shown below.

// define variables
int a = 10, b = 20;
int sum = a + b; 
// create a new StringBuilder object
StringBuilder sb = new StringBuilder();
// append some strings to the StringBuilder
sb.append("Sum ");
sb.append("of ");
sb.append(a);
sb.append(" and ");
sb.append(b);
sb.append(" is ");
sb.append(sum);
// convert the contents of the StringBuilder to a string
String str = sb.toString();
System.out.println(str);

Output is

Sum of 10 and 20 is 30

Note that append() returns the same StringBuilder object on which it was invoked.
This means that you can chain multiple calls to append(). So, above code can be modified as

StringBuilder sb = new StringBuilder(); 
sb.append("Sum ").
append("of ").
append(a).
append(" and ").
append(b).
append(" is ").
append(sum);

4. Apache Commons Text
Apache Commons Text library has a StringSubstitutor class which can substitute variables in a string with their values.
We create a java map with variable names as keys and their values as map values. This map is supplied to StringSubstitutor with its constructor.
Then, we invoke its replace() method providing it the string containing those variable names.
Remember that variables should be enclosed between ${} as stated by StringSubstitutor documentation.

This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}.

Example,

Map<String, Object> vars = new HashMap<>();
vars.put("a", 10);
vars.put("b", 20);
vars.put("sum", a+b);
StringSubstitutor sb = new StringSubstitutor(vars);
String str = sb.replace("Sum of ${a} and ${b} is ${sum}");
System.out.println(str);

Output is

Sum of 10 and 20 is 30

You can also use replace() method without creating an object as there is a static method as well, which accepts a map and string as arguments as shown below

Map<String, Object> vars = new HashMap<>(); 
vars.put("a", 10); 
vars.put("b", 20); 
vars.put("sum", a+b); 
String str = StringSubstitutor.replace(
               "Sum of ${a} and ${b} is ${sum}", vars);

5. Concatenation
Strings can be interpolated with plus(+) operator.
You can also add variables to strings, in which case, their values are added to the resultant string. Example,

int a = 10, b = 20;
int sum = a + b;
String s = "Sum of " + a + 
           " and "+ b + " is " + sum;

Note that adding multiple strings with + is not considered a good practice since it will create multiple string objects.
This is because string objects are immutable, meaning that you cannot change its value after creation.

Hope the article was useful.