String interpolation in Java 14 or 15

Viewed 16580

Since I am using Java 14 and 15 preview features. Trying to find the string interpolation in java.

The closest answer I found is

String.format("u1=%s;u2=%s;u3=%s;u4=%s;", u1, u2, u3, u4)

Since the answer which I got from lots fo references are old answers asked 4,5 years ago. Is there any update on the string interpolation in java 11,12,13,14,15 equivalent to C#

string name = "Horace";
int age = 34;
Console.WriteLine($"Your name is {name} and your age {age}");
5 Answers

There is something slightly closer; an instance version of String::format, called formatted:

String message = "Hi, %s".formatted(name);

It is similar to String::format, but is more friendly to use in chained expressions.

To my knowledge, there are no updates in the standard java libraries regarding such kind of string formatting.

In other words: you are still "stuck" with either using String.format() and its index based substitution mechanism, or you have to pick some 3rd party library/framework, such as Velocity, FreeMarker, ... see here for an initial overview.

There is no built-in support for that currently, but Apache Commons StringSubstitutor can be used.

import org.apache.commons.text.StringSubstitutor;
import java.util.HashMap;
import java.util.Map;
// ...
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"

Looks like nice C# interpolation si not working in these java version at all. Why we need this - to have nice and readable lines of code dumping text to Log files. Below is the sample code that works (there is commented org.apache.commons.lang3.StringUtils which at some point of writting was required but later it was not) - it was dropping ClassNotFound or other NotFoundException - I have not investigated it.

The StringSubstitutor might be later packed in something nicer that will make it easier to use for Log message dumping

package main;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.text.*;
//import org.apache.commons.lang3.StringUtils;

public class Main {

    public static void main(String[] args) {
        System.out.println("Starting program");
        
        var result =  adding(1.35,2.99);

        Map<String, String> values = new HashMap<>();
        values.put("logMessageString", Double.toString(result) );

        StringSubstitutor sub = new StringSubstitutor(values);
        sub.setEnableSubstitutionInVariables(true);
        String logMessage = sub.replace("LOG result of adding: ${logMessageString}");

        System.out.println(logMessage);
        System.out.println("Ending program");
         
    }
    // it can do many other things but here it is just for prcoessing two variables 
    private static double adding(double a, double b) {
        return a+b;
    }

}

You can also use MessageFormat like this (Java 5.0 or later)

MessageFormat.format("Hello {0}, how are you. Goodbye {0}",userName);

Very nice

Related