It works same as printf() of C.

%s for String 
%d for int 
%f for float

ahead

String.format("%02d", 8)

OUTPUT: 08

String.format("%02d", 10)

OUTPUT: 10

String.format("%04d", 10)

OUTPUT: 0010

so basically, it will pad number of 0's ahead of the expression, variable or primitive type given as the second argument, the 0's will be padded in such a way that all digits satisfies the first argument of format method of String API.

Answer from Hiren on Stack Overflow
🌐
W3Schools
w3schools.com › java › ref_string_format.asp
Java String format() Method
Note: You will find more "Try it Yourself" examples at the bottom of this page. The format() method returns a formatted string using a locale, format and additional arguments.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Formatter.html
Formatter (Java Platform SE 8 )
July 21, 2026 - Java™ Platform Standard Ed. 8 ... An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as byte, BigDecimal, and Calendar are supported.
Discussions

How to format strings in Java - Stack Overflow
There are plenty of ways to format Strings using external libraries. They add little to no benefit if the libraries are imported solely for the purpose of String formatting. Few examples: Apache Commons: StringSubstitutor, examples in its JavaDoc. More on stackoverflow.com
🌐 stackoverflow.com
What's the difference between String.format() and str. ...
Returns a formatted string using the format string and arguments. It's a static method of String class. It's introduced in Java SE 5 [since 2004]. More on stackoverflow.com
🌐 stackoverflow.com
String.format() is 3x faster in Java 17
Glad to see some of the small enhancements we did in 17 get recognition. Not sure if this one matters, but String::format shows up in profiles every now and then so it felt reasonable to me to give it some TLC in between larger projects. More on reddit.com
🌐 r/java
41
298
October 30, 2021
is there any difference between using string.format() or an fstring?
Don't forget that f-strings haven't been around forever. It may be partly old habits, it may be not keeping up to date with features, they may still be wanting to target a minimum python version that didn't support f-strings. I'd tend to prefer to use f-strings, but I wouldn't crucify someone for using perfectly valid language constructs. More on reddit.com
🌐 r/Python
145
317
October 9, 2022
🌐
Baeldung
baeldung.com › home › java › java string › java string.format()
Java String.format() | Baeldung
March 23, 2026 - For format specifiers that don’t correspond to arguments, the conversion is a character indicating content to be inserted in the output. ... The behavior of a null argument depends on the conversion. For example, characters s and S evaluate to null if the argument arg is null. Let’s demonstrate string formatting with an example JUnit test method:
🌐
Jmu
wiki.cs.jmu.edu › reference › java › formatting
Formatting Strings and Output in Java - JMU CS Wiki
January 26, 2026 - The static format() method in the String class is passed one parameter called a format string and then any number of other parameters. In the above example, the format string is "CS=" and the one other parameter is course. A format string consists of String literals and format specifiers.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-string-format-method-with-examples
Java String format() Method - GeeksforGeeks
June 2, 2026 - IllegalFormatException:If the format specified is illegal or there are insufficient arguments. Example: Using String.format() method to show concatinate the two floating values of given variable using /.
Find elsewhere
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › How-to-format-a-Java-String-with-printf-example
How to format a Java String with printf in Java 25
Java 25 makes simple programs concise with compact source files, instance main methods and the new IO class, with no preview flags required. ... Use %s and %S, String.formatted, field width and Java 25's IO class to format aligned, uppercase and tabular String output.
Published: December 8, 2025
🌐
Kansas State University
textbooks.cs.ksu.edu › cc210 › 09-strings › 06-java › 04-formatting
String Formatting :: CC 210 Textbook
3 weeks ago - 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. Here’s an example of how to use that method in Java:
Top answer
1 of 12
323

Take a look at String.format. Note, however, that it takes format specifiers similar to those of C's printf family of functions -- for example:

String.format("Hello %s, %d", "world", 42);

…would return "Hello world, 42". The "format string" link points to the complete official spec, but for simple cases, this much shorter documentation may be helpful for an introduction to format specifiers even though it's outdated and about Lava. The most commonly used ones are:

  • %s - insert a string
  • %d - insert a signed integer (decimal)
  • %f - insert a real number, standard notation

This is radically different from C#, which uses positional references with an optional format specifier. That means that you can't do things like:

String.format("The {0} is repeated again: {0}", "word");

... without actually repeating the parameter passed to printf/format. (see The Scrum Meister's comment below)


If you just want to print the result directly, you may find System.out.printf (PrintStream.printf) to your liking.

2 of 12
182

In addition to String.format, also take a look java.text.MessageFormat. The format less terse and a bit closer to the C# example you've provided and you can use it for parsing as well.

For example:

int someNumber = 42;
String someString = "foobar";
Object[] args = {new Long(someNumber), someString};
MessageFormat fmt = new MessageFormat("String is \"{1}\", number is {0}.");
System.out.println(fmt.format(args));

A nicer example takes advantage of the varargs and autoboxing improvements in Java 1.5 and turns the above into a one-liner:

MessageFormat.format("String is \"{1}\", number is {0}.", 42, "foobar");

MessageFormat is a little bit nicer for doing i18nized plurals with the choice modifier. To specify a message that correctly uses the singular form when a variable is 1 and plural otherwise, you can do something like this:

String formatString = "there were {0} {0,choice,0#objects|1#object|1<objects}";
MessageFormat fmt = new MessageFormat(formatString);
fmt.format(new Object[] { new Long(numberOfObjects) });
🌐
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 ...
In this example, we fill the additional spaces with 0: int number = 10; // `d` specifies the number will be returned with 5 characters in it, extra digits will be filled with 0 String formatted = String.format("Number [d]", number); System.out.println(formatted); // Prints: Number [00010] ...
Top answer
1 of 2
37

Make sure you use a good IDE so that you have easy access to browse into JDK source code. In Eclipse say, use F3 to open to any declaration. IntelliJ IDEA has similar feature.

If you view the source code for both methods, you can see these calls are identical except that variables this is interchanged with format when comparing the instance vs static method:

public String formatted(Object... args) {
    return new Formatter().format(this, args).toString();
}
public static String format(String format, Object... args) {
    return new Formatter().format(format, args).toString();
}

So as you've observed: String.format(str, args) is same as str.formatted(args)

2 of 2
22

Text Blocks were finalized and permanently added in JDK 15 and some additional methods added to support text blocks. One of this methods is:

String::formatted(Object... args)

And I know the functions of two codes below are the same.

As you mentioned in your question both methods do the same job and return same results. The goal of introducing such a method is:

simplify value substitution in the Text Block.

Based on JEP (JDK Enhancement Proposals) 378:

Text blocks do not directly support string interpolation. Interpolation may be considered in a future JEP. In the meantime, the new instance method String::formatted aids in situations where interpolation might be desired.

As an example you consider this code segment:

String code = String.format("""
      public void print(%s o) {
          System.out.println(Objects.toString(o));
      }
      """, type);

We can change it using formatted method as:

String source = """
        public void print(%s object) {
            System.out.println(Objects.toString(object));
        }
        """.formatted(type);

Which is cleaner.



Also consider these minor differences between them when using the methods:

public static String format(String format, Object... args)
  • Returns a formatted string using the format string and arguments.
  • It's a static method of String class.
  • It's introduced in Java SE 5 [since 2004].

public String formatted(Object... args)
  • Formats using this string as the format string, and the supplied arguments.
  • It's an instance method of String class.
  • It's introduced in Java SE 15 (JDK 15) [since 2020].
  • This method is equivalent to String.format(this, args)
🌐
Medium
medium.com › kwal-it › how-to-format-a-string-in-java-950d07ea8be6
How To Format A String in Java. Formatted is the new kid in town | by Dieter Jordens | Kwal-IT | Medium
May 2, 2024 - Since Java 15, you can now format a String with a new method, formatted. This method is the same as the well know static String format method.
🌐
DZone
dzone.com › coding › java › formatting strings in java: string.format() method
Formatting Strings in Java: String.format() Method
November 13, 2024 - Core Java Specialization | Enroll in Free Online Course Today* ... There are three primary ways to format a string in Java. You can use the String.format() method, the printf() method, or the MessageFormat class for formatting strings.
🌐
Reddit
reddit.com › r/java › string.format() is 3x faster in java 17
r/java on Reddit: String.format() is 3x faster in Java 17
October 30, 2021 - I don't know what you mean by "running without reflection" - the method Formatter.parse(List, String) is not publicly accessible. ... Be careful what you measure. Allocating stuff is cheap in java, but not free.
🌐
Tutorialspoint
tutorialspoint.com › java › lang › string_format.htm
Java - String format() Method
In the following example, we are creating an object of the string class with the value "TutorialsPoint". Using the format() method, we are trying to get the formatted string of the current string in the specified format. package com.tutorialspoint; import java.util.Locale; public class Format { public static void main(String[] args) { // create an object of the string class String str = new String("TutorialsPoint"); // initialize the double variable Double d = 234.454d; System.out.println("The given string is: " + str); System.out.println("The given double value is: " + d); // use format() method String new_str; String new_str1; new_str = String.format("Welcome to the %s", str); new_str1 = String.format("The result is: f", d); System.out.println("The formatted string is: " + new_str); System.out.println("The formatted value is: " + new_str1); } }
🌐
Dot Net Perls
dotnetperls.com › format-java
Java - String.format Examples - Dot Net Perls
This example uses String.format with a Calendar date. We use "t" and then "B" to insert the long month string. With "t" and then "e" or "Y" we insert the day or year numbers. Note We use the "%1" at the start of the insertion points to indicate "the first argument" after the format string. import java.util.Calendar; public class Program { public static void main(String[] args) { // Create a calendar with a specific date....
🌐
CodeJava
codejava.net › java-se › file-io › java-string-format-examples
Java String Format Examples
July 29, 2019 - List<String> listBook = Arrays.asList( "Head First Java", "Effective Java", "The Passionate Programmer", "Head First Design Patterns" ); for (String book : listBook) { System.out.format("%-30s - In Stock%n", book); }Output: The following example prints numbers in both decimal format (%d) and hexadecimal format (%x and %#x):
🌐
Attacomsian
attacomsian.com › blog › java-string-format
How to format a string in Java
October 29, 2022 - The String.formatted() method was introduced in Java 15 for formatting an instance of the String class using the supplied arguments.
🌐
xperti
xperti.io › home › how to format a string in java with examples
What Is Java String Format And How To Use It?
May 5, 2022 - This includes other classes like FileWriter, PrintWriter, PrintStream, BufferedWriter, StringBuffer and others. Similar to the format() method, Formatter class also allows the use of all format specifiers, escape characters, locale and all other features mentioned with the printf() method. This is one unique Java string format technique that does not make use of Formatter class, unlike every other method we have discussed so far.
🌐
Protocol Buffers
protobuf.dev › programming-guides › proto3
Language Guide (proto 3) | Protocol Buffers Documentation
This is useful if you are defining ... message type, you could add it to the same .proto: message SearchRequest { string query = 1; int32 page_number = 2; int32 results_per_page = 3; } message SearchResponse { ......