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.
Discussions

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
Help with String.format
Why are you chaining the Strings with concatenation? String.format works totally different from what you do with it. With String.format you don't concatenate, you write your text with placeholders and add the values separated by commas after the text: String info = String.format("The movie %15s was directed by %15s and cost %.3f to make.", this.getTitle(), this.getDirector(), this.getProductionCost()); See: String.format and Formatter as well as the Formatting Numeric Print Output Tutorial More on reddit.com
🌐 r/learnjava
10
3
October 18, 2016
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Formatter.html
Formatter (Java Platform SE 8 )
April 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.
🌐
Baeldung
baeldung.com › home › java › java string › java string.format()
Java String.format() | Baeldung
March 23, 2026 - A quick example and explanation of the format API of the standard String class in Java.
🌐
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 /.
🌐
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. Here’s an example of how to use that method in Java:
Find elsewhere
Top answer
1 of 2
36

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
20

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)
🌐
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.
🌐
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] ...
🌐
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 example
Use %S as the printf String specifier to output upper-case text. Precede the letter s with a number to specify field width. Put a negative sign after the % to left-justify the text.
🌐
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
June 1, 2023 - 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 most common way of formatting a string in Java is using the String.format() method.
🌐
Java String
javastring.net › home › java string format() method examples
Java String format() Method Examples
July 15, 2019 - format(Locale l, String format, Object… args): This method uses the given locale for the formatting. These methods throw IllegalFormatException if the format has invalid specifiers, insufficient, or wrong type of arguments. The java.util.Formatter class provides support for creating a formatted string.
🌐
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 { ......
🌐
Swagger
swagger.io › specification
OpenAPI Specification - Version 3.1.0 | Swagger
If it were treated as application/json, then the serialized value would be a JSON string including quotation marks, which would be percent-encoded as ". Here is the id parameter (without address) serialized as application/json instead of text/plain, and then encoded per RFC1866: Note that application/x-www-form-urlencoded is a text format, which requires base64-encoding any binary data: Given a name of example and a solid red 2x2-pixel PNG for icon, this would produce a request body of:
🌐
DigitalOcean
digitalocean.com › community › tutorials › java-printf-method
Java printf() - Print Formatted String to Console | DigitalOcean
August 3, 2022 - jshell> float y = 2.28f y ==> 2.28 jshell> System.out.printf("Precision formatting upto 4 decimal places %.4f\n",y) Precision formatting upto 4 decimal places 2.2800 jshell> float z = 3.147293165f z ==> 3.147293 jshell> System.out.printf("Precision formatting upto 2 decimal places %.2f\n",z) Precision formatting upto 2 decimal places 3.15 · As you can see it rounds off to the next decimal in the second case. In this section, we’ll see three examples for each of these: