Primitive question, but how do I format strings like this:
\"Step {1} of {2}\"
by substituting variables using Java? In C# it\'s
There is a new instance method called String::formatted(Object... args) as of Java 15.
The internal implementation is same to String::format(String format, Object... args).
Formats using this string as the format string, and the supplied arguments.
String step1 = "one";
String step2 = "two";
// results in "Step one of two"
String string = "Step %s of %s".formatted(step1, step2);
Advantage: The difference is that the method is not static
and the formatting pattern is a string itself from which a new one is created based on the args
. This allows chaining to build the format itself first.
Disadvantage: There is no overloaded method with Locale
, therefore uses the default one. If you need to use a custom Locale
, you have to stick with String::format(Locale l,String format,Object... args).