Java does not have a current, built-in f-string syntax like Python’s f"Hello, {name}". For formatted output, use String.format(), String.formatted(), or a formatter such as System.out.printf(); Java’s experimental string templates are a separate, withdrawn preview feature.
What “f-string” means in Java
An f-string is Python’s way to place expressions inside a string literal and have them evaluated. For example, Python code might write f"Hello, {name}". Java does not recognize that syntax: writing f"Hello, {name}" in ordinary Java source will not interpolate name and is not valid Java syntax.
Java developers often use “f-string” informally to ask how to build a string that mixes fixed text with variable values. The closest practical answer depends on the need:
- For a formatted string value, use
String.format()orString.formatted(). - To print formatted output directly, use
System.out.printf(). - For simple combinations, use the
+operator. - For localized messages, consider
MessageFormator resource bundles.
These choices are established Java APIs. They use formatting patterns or concatenation rather than Python-style braces containing Java expressions.
Java’s preview string templates
Java did experiment with syntax that looks more like interpolation. In the preview feature introduced by JEP 430 in JDK 21, a template could be written as STR."Hello, \{name}!". The expression inside \{...} was evaluated, and the STR processor combined it with the surrounding text. A more involved expression could appear inside the braces, just as it can in ordinary Java code.
String templates were designed to do more than substitute values. A template processor receives the text fragments and the evaluated expressions, then decides how to produce a result. The built-in STR processor produced a string; custom processors could apply other behavior. This processor model was intended to support uses such as structured data and safer handling of particular inputs, rather than hard-coding interpolation as the only possible outcome.
However, a preview feature is not the same as a permanent Java language feature. The syntax was previewed in JDK 21 and again in JDK 22, then withdrawn from the JDK 23 feature set. It should not be presented as syntax supported by current Java releases. If you encounter STR."..." in an article or code example, check which JDK preview it describes before trying to use it.
Use String.format for formatted values
String.format() is a common choice when you want a completed string and need control over how values appear. It uses format specifiers beginning with %. For example:
%sinserts a string representation of a value.%dformats an integer as a decimal number.%fformats a floating-point number.%.2fformats a floating-point number with two digits after the decimal point.%ninserts the platform’s line separator, and%%represents a literal percent sign.
For example, given String name = "Mina"; and int tasks = 3;, String message = String.format("%s has %d tasks", name, tasks); produces Mina has 3 tasks. With double price = 12.5;, String label = String.format("Price: $%.2f", price); produces a value such as Price: $12.50 under a locale that uses a period as its decimal separator.
The format string and the arguments are separate. The first %s, %d, or other conversion generally corresponds to the first argument, the next conversion to the next argument, and so on. This makes formatting patterns reusable, but it also means a mismatch can cause an exception at runtime or produce the wrong output. Keep the format pattern and argument list in sync.
Use formatted() for a shorter call
Since Java 15, String has an instance method named formatted(). It applies formatting to the string on which it is called, so the pattern can appear before the arguments:
String message = "%s has %d tasks".formatted(name, tasks);
This produces the same kind of result as String.format("%s has %d tasks", name, tasks). The format syntax remains percent-based; formatted() does not add brace interpolation or turn Java into a language with f-strings. Use it when its compact style improves readability, and use String.format() when a static method makes the relationship between the pattern and arguments clearer.
Choose between formatting and concatenation
For a short message with just a couple of values, concatenation can be easy to read: String message = "Hello, " + name + "!";. It is familiar Java syntax and does not require a format pattern. For fixed-width output, decimal precision, or a string with several substitutions, a formatter usually makes the intended layout more explicit.
A useful rule of thumb is:
- Choose concatenation for simple, small combinations where no special formatting is needed.
- Choose
String.format()orformatted()when width, precision, alignment, or several typed substitutions matter. - Choose
printf()when the formatted result should be written directly to a stream rather than saved as a string. - Choose
MessageFormator resource bundles when messages need localization and translators may need to rearrange values.
Java’s compiler may optimize string concatenation, so replacing every + with a formatter is not automatically faster. Prefer the option that makes the code understandable; measure performance only if string construction is a demonstrated bottleneck.
Locale, precision, and common formatting mistakes
Number formatting can depend on locale. A decimal value may be displayed with a period in one locale and a comma in another. If output must be stable—for example, a machine-readable value or a log format—choose a locale explicitly, such as with String.format(Locale.ROOT, "%.2f", value), and import java.util.Locale. If the text is intended for people in different regions, select a suitable locale rather than assuming one punctuation convention.
Check the conversion type as well as the number of placeholders. Using %d for a floating-point value is not equivalent to rounding it, and a mismatch between a conversion and its argument can throw IllegalFormatConversionException. For positional reuse, Java’s formatter supports indexes such as %1$s and %1$d; this can be useful when a value appears more than once, but it can make a pattern harder to scan.
Another common mistake is expecting braces to be special to Java formatting. In String.format("Hello, {0}", name), {0} is not a String.format() placeholder. Percent-based formatting uses %s; MessageFormat, by contrast, uses numbered placeholders such as {0}. Match the pattern syntax to the API you actually call.
Security: formatting is not input sanitization
Inserting a value into a string does not automatically make that value safe for every destination. A formatted SQL string can still be vulnerable to SQL injection if untrusted input is inserted into the query text. Use a PreparedStatement with parameters for SQL values instead of relying on String.format() or concatenation.
The same general caution applies to HTML, shell commands, and other structured formats: ordinary string formatting does not escape values according to the rules of those formats. Use the appropriate library or parameterized API for the destination. Java’s preview string templates were not a universal escaping mechanism either; a processor would need to provide and guarantee the relevant handling.
Frequently Asked Questions
Does Java have f-strings?
No. Standard Java does not support Python-style f-strings. Use String.format(), String.formatted(), concatenation, or an API suited to the output you need.
What is the Java equivalent of Python f-strings?
For many everyday cases, String.format("Hello, %s", name) or "Hello, %s".formatted(name) is the closest established alternative. Both use percent placeholders rather than embedded expressions in braces.
Can I use STR string templates in Java 21?
They were available as a preview feature in JDK 21 and JDK 22, so using them required preview-feature support and the appropriate preview compiler and runtime options. The feature was withdrawn in JDK 23, so it is not a portable choice for current Java code.
What is the difference between printf() and String.format()?System.out.printf() formats and writes output to a print stream. String.format() returns the formatted text as a String, which you can store, pass, or print later.
Does String.formatted() use curly braces?
No. It uses the same percent-based format specifiers as String.format(), such as %s and %.2f. Curly-brace placeholders belong to other conventions or APIs, not this method.
Related
- A/B Split Testing: Meaning, Method, and Common Mistakes
- Balance of Payments Theory: Meaning and How It Works
- Bullseye Graphic in PowerPoint: Make One Cleanly
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Remove a Horizontal Page Break in Excel QuicklyTo remove a manual horizontal page break in Excel for Microsoft 365 on Windows, select the row immediately…
- How to Open a TXT File in Excel Without Losing DataTo open a TXT file in Excel for Microsoft 365 on Windows, choose Data > From Text/CSV, select…
- Excel Cell Lock: How to Unlock or Remove ProtectionTo remove a cell lock in Excel, select the cell, press Ctrl+1, open the Protection tab, clear Locked,…
- View Mail Merge Rules in Word and Edit Their FieldsIn Microsoft Word for Microsoft 365 on Windows, open the merge document and choose Mailings > Rules to…
- How to Align a Picture in an Excel Cell: Step by StepTo put a picture in an Excel cell, select the cell and choose Insert > Pictures > Place…
- Excel Attendance Point Tracker Template: Setup & UseYes, an Excel attendance point tracker template is a spreadsheet that automatically converts absences, tardies, and early departures…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.