See String.format method.
String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
Answer from Grzegorz Żur on Stack OverflowSee String.format method.
String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
StrSubstitutor from Apache Commons Lang may be used for string formatting with named placeholders:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.1</version>
</dependency>
https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html :
Substitutes variables within a string by values.
This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods.
Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.
Example:
String template = "Hi ${name}! Your number is ${number}";
Map<String, String> data = new HashMap<String, String>();
data.put("name", "John");
data.put("number", "1");
String formattedString = StrSubstitutor.replace(template, data);
How to do string formatting with placeholders in Java (like in Python)? - Stack Overflow
String template with named placeholders
Replacing multiple string placeholders with values.
How to use integers in a String with placeholders
The MessageFormat class looks like what you're after.
System.out.println(MessageFormat.format("{0} + {1} = {2}", x, y, x + y));
Java has a String.format method that works similarly to this. Here's an example of how to use it. This is the documentation reference that explains what all those % options can be.
And here's an inlined example:
package com.sandbox;
public class Sandbox {
public static void main(String[] args) {
System.out.println(String.format("It is %d oclock", 5));
}
}
This prints "It is 5 oclock".