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 Overflow
🌐
Baeldung
baeldung.com › home › java › java string › named placeholders in string formatting
Named Placeholders in String Formatting | Baeldung
August 27, 2025 - So, StringSubstitutor treats the literal ${number} as a parameter placeholder, too. In fact, StringSubstitutor‘s Javadoc has stated this case:
Discussions

How to use integers in a String with placeholders
why is currentDate not updating when I update/change currentDay or currentMonth? Because currentDate is created when you call String.format, and it doesn't change. It's not bound to those variables, it just grabs their current value, converts them to strings, and inserts those strings into the template string. You'd have to call String.format again. More on reddit.com
🌐 r/learnprogramming
11
0
November 3, 2022
String template with named placeholders
Thanks for all responses, please note, My question was specifically for named placeholders not positional, and I am looking for a template system, i.e. something to be able to reuse and plug in different values, not for an interpolated string where the variables have to be predefined in scope More on reddit.com
🌐 r/learnprogramming
7
1
July 14, 2022
There will be no String Template in JDK 23.
wow. It's interesting that Brian Goetz recently said he was ready to finalize the feature and move on, and all the complaints were nothing they hadn't anticipated and discussed extensively. They had the JEP submitted to finalize this for Java 22 and they held off to a second unchanged preview, and then were going to finalize for Java 23, and now, even Goetz is ready to move the whole thing back to a complete redesign. As a Java dev I'd rather get this later with a better design than earlier with a less perfect design. It is interesting how close the existing design was to being finalized. The preview system works :) More on reddit.com
🌐 r/java
131
122
April 6, 2024
JEP: String Templates (Final) for Java 22
I have read the explanation by various members of the OpenJDK team as to why that syntax was chosen and I still don't understand it. Even Brian's explanation, which otherwise gets right through to me even on more complex topics, did not really clarify it for me. He says choosing ${} would have made all the existing Strings a template if they contain ${} with a valid variable in the same scope, which breaks compatibility. But I don't know what I am missing to not see the breakage. For an existing String literal having a ${...} does not make it into a template that will be processed. You have to explicitly invoke STR. on that to process it as a template. Else if will be just like any other String with no interpolation. STR. is a completely new feature and is illegal in prior versions so I don't see how this breaks compatibility. Even if you had a variable named STR in existing code, it is illegal to do STR."some str literal". I guess it is too late now. More on reddit.com
🌐 r/java
133
72
October 1, 2023
🌐
W3Schools
w3schools.com › java › ref_string_format.asp
Java String format() Method
If a locale is not passed to this method then the locale given by Locale.getDefault() is used. Data from the additional arguments is formatted and written into placeholders in the format string, which are marked by a % symbol.
🌐
Kansas State University
textbooks.cs.ksu.edu › cc210 › 09-strings › 06-java › 04-formatting
String Formatting :: CC 210 Textbook
June 27, 2024 - Java also includes a special string method, the format() method, which allows us to use placeholders in our output string, and then replace those placeholders with the values stored in variables.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-illustrate-string-interpolation
String Interpolation in Java - GeeksforGeeks
July 23, 2025 - The String format() method in Java uses placeholders, for example, "%s" to insert variable values into a string, with the variables provided as additional arguments after the format string.
🌐
Belief Driven Design
belief-driven-design.com › looking-at-java-21-string-templates-c7cbc
Looking at Java 21: String Templates | belief driven design
June 20, 2023 - Whenever we have a String-based template that requires transformation, validation, or sanitizing, Java’s String templates will give us a built-in simplistic template engine without requiring a third-party dependency. To not start from zero, the Java platform provides two additional template processors besides STR. Be aware that the additional template processors seem to be missing-in-action in Java 21.ea.27. At least I didn’t get it to work in my test setup. The processor FMT combines the interpolation power of STR with the format specifiers defined in java.util.Formatter:
🌐
CodeSignal
codesignal.com › learn › courses › java-string-manipulation-for-beginners › lessons › string-formatting-in-java-enhancing-readability-of-your-data
String Formatting in Java: Enhancing Readability of Your ...
Java · String name = "Tom"; String greeting = String.format("Hello, %s!", name); System.out.println(greeting); // Prints: Hello, Tom! In this instance, we used %s - a placeholder for a string - that gets replaced by the string Tom. The other available options include: %d - integer number ·
🌐
Sarthaks eConnect
sarthaks.com › 3496942 › explain-java-string-format-method
Explain Java String format() Method - Sarthaks eConnect | Largest Online Education Community
April 29, 2023 - LIVE Course for free · The Java String format() method is used to create formatted strings by replacing placeholders with actual values. The method takes a format string and a variable number of arguments, which will be used to replace the ...
Find elsewhere
🌐
Reddit
reddit.com › r/learnprogramming › how to use integers in a string with placeholders
r/learnprogramming on Reddit: How to use integers in a String with placeholders
November 3, 2022 -

Hi, Im new to learning Java and have been trying to format a String so i can just call it with Sys.out rather than having to type the entire String each time, however it doesn't seem to update. My code is below

int currentDay = 1;
int currentMonth = 2;
		
String currentDate = String.format("The current date is: %d of %d", currentDay, currentMonth);
		
System.out.println(currentDate);
		
Scanner in = new Scanner(System.in);
		
System.out.println("New day: ");
currentDay = in.nextInt();
		
System.out.println("New Month: ");
currentMonth = in.nextInt();
		
System.out.println(currentDate);

why is currentDate not updating when I update/change currentDay or currentMonth? I thought I could change integers as a program goes but currentDate will continue to print out 1 and 2 despite the in.nextInt. Any help would be appreciated.

🌐
HappyCoders.eu
happycoders.eu › java › string-templates
String Templates in Java
June 12, 2025 - String interpolated = STR."\{a} times \{b} = \{Math.multiplyExact(a, b)}";Code language: Java (java) The placeholder may also contain quotes, and for the sake of clarity, you can split it over multiple lines and add comments (at this point, I need to turn off the WordPress syntax highlighting plugin, as the following code will overwhelm it): String dateMessage = STR."Today's date: \{ LocalDate.now().format( // We could also use DateTimeFormatter.ISO_DATE DateTimeFormatter.ofPattern("yyyy-MM-dd") )}";Code language: plaintext (plaintext)
🌐
JetBrains
blog.jetbrains.com › home › intellij idea › string templates in java – why should you care?
String Templates in Java - why should you care? - The JetBrains Blog
November 27, 2023 - Let’s try the next option, that is, replace the original String concatenation using the + operator with the formatted() method in the String class. Don’t worry about the syntax, invoke the context actions and select it from the popup menu, as follows: It solved one issue and introduced another. Now you can clearly see where the literal strings have spaces or a comma. But now you need to refer back and forth between the placeholders %d, %s and the variable names, to find out which variable value will be inserted where.
🌐
Medium
medium.com › tuanhdotnet › 7-essential-techniques-for-string-formatting-in-java-072b60235fc0
7 Essential Techniques for String Formatting in Java | by Anh Trần Tuấn | tuanhdotnet | Medium
June 23, 2025 - String.format() is one of the most ... for easy interpolation. String.format() allows you to embed placeholders within a string, specifying the format for each placeholder and then supplying values....
🌐
Reddit
reddit.com › r/learnprogramming › string template with named placeholders
r/learnprogramming on Reddit: String template with named placeholders
July 14, 2022 -

Imagine the following piece of code

Template("Hello {name}, you are {position} in line").format(name="Alice", position=12, extra=42) 

Would you rather that an error be thrown due to an unbound key (extra) being passed or should it be ignored?

I didn't find much languages even having such string templating built in except other than Python (string.format) and Rust (format!), in Python the extra key/value is ignored, while Rust will throw an exception.

What would be your approach?

Top answer
1 of 2
1
Thanks for all responses, please note, My question was specifically for named placeholders not positional, and I am looking for a template system, i.e. something to be able to reuse and plug in different values, not for an interpolated string where the variables have to be predefined in scope
2 of 2
1
There are 'format strings' in many languages... eg. Java "Hello %s, you are %d in line".formatted("Alice", 12, 42) I think many languages silently ignore the unbound param (though many IDE's can report it) - since the params list might not be dynamic (that is it may be a literal param list in the code as opposed to data), but the formatting template could be dynamic. An alternative is String Interpolation, which is available in many languages. Java, which lacks it, is investigating adding the feature - from their feature proposal we can see the following: Language | Example | JavaScript | ${x} plus ${y} equals ${x + y} (uses backticks) | C# | $"{x} plus {y} equals {x + y}" | Visual Basic | $"{x} plus {y} equals {x + y}" | Scala | f"$x%d plus $y%d equals ${x + y}%d" | Python | f"{x} plus {y} equals {x + y}" | Ruby | "#{x} plus #{y} equals #{x + y}" | Groovy | "$x plus $y equals ${x + y}" | Kotlin | "$x plus $y equals ${x + y}" | Swift | "(x) plus (y) equals (x + y)" I think Rust would be something like format!("{} plus {} equals {}", x, y, x + y) or format!("{x} plus {y} equals {}", x + y) The types of expressions and formatting specifiers that can be embedded in the template itself vary a lot by language. Java is proposing something like STR."\{x} + \{y} = \{x + y}" The STR. prefix exists because the feature is expandable to include other consumers of the template that might want to do different enforcement / checking and produce a type other than a String - eg an SQL processor validating/escaping the SQL, and generating an SQL request with the expressions as SQL params instead of literals. In many cases, a benefit of interpolation is not just readability/brevity, but also that the validation is a compile-time exercise and I expect most compile-time languages would expect unbound params or values to be a compile-time error. Edit: Actually include the String Template proposal link.
🌐
Vultr Docs
docs.vultr.com › java › standard-library › java › lang › String › format
Java String format() - Format String Text | Vultr Docs
December 20, 2024 - The format() method in Java is a versatile tool provided in the String class to format strings. It allows you to construct formatted strings with placeholders, making it highly useful for creating dynamic content where variable values need to ...
🌐
Belief Driven Design
belief-driven-design.com › formatting-strings-with-java-42648c25697
Formatting Strings With Java | belief driven design
April 14, 2020 - We all know String.format(...). But there are other options. Java has multiple ways of formatting, aligning, padding, and justifying Strings.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › How-to-format-a-Java-int-with-printf-example
How to format a Java int or long with printf example
Use %d as the placeholder specifier. Precede the letter d with a comma to add a thousands group separator. Add additional parameters to left or right justify, add a plus sign, or zero pad.
🌐
Baeldung
baeldung.com › home › java › java string › string templates in java
String Templates in Java | Baeldung
July 7, 2025 - String composeUsingFormatters(String feelsLike, String temperature, String unit) { return String.format("Today's weather is %s, with a temperature of %s degrees %s", feelsLike, temperature, unit); } The base template string remains static. However, the order and number of arguments passed here are crucial for the correctness of its response. Java provides a MessageFormat class of the Java.text package that helps in the composition of text messages with placeholders for dynamic data.
🌐
GitHub
google.github.io › mug › apidocs › com › google › mu › util › StringFormat.html
StringFormat (mug-root 10.5.2-SNAPSHOT API)
Parses input and applies mapper with the single placeholder value in this format string. ... Unlike parse(String, Function), IllegalArgumentException is thrown if the input string doesn't match the string format. The error message will include both the input string and the format string for ease of debugging, but is otherwise generic. If you need a different exception type, or need to customize the error message, consider using AbstractStringFormat.<R>parse(java.lang.String,java.util.function.Function<? super java.lang.String,? extends R>) instead and call Optional.orElseThrow() explicitly.
🌐
Sololearn
sololearn.com › en › Discuss › 1178226 › variable-placeholder-difference
Variable & Placeholder difference
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
Baeldung
baeldung.com › home › java › java string › string interpolation in java
String Interpolation in Java | Baeldung
July 23, 2025 - Another approach is using the format() method from the String class. Contrary to the “+” operator, in this case we need to use placeholders to get the expected result in the String interpolation: @Test public void givenTwoString_thenInterpolateWithFormat() { String EXPECTED_STRING = "String Interpolation in Java with some Java examples."; String first = "Interpolation"; String second = "Java"; String result = String.format("String %s in %s with some %s examples.", first, second, second); assertEquals(EXPECTED_STRING, result); }