java.lang.StringBuilder

System.out.println(new StringBuilder("I like")
                   .append(cake)
                   .append(" and I eat ")
                   .append(cakeNumber)
                   .append(" blah blah     prolonging this string because ")
                   .append(whyNot)
                   .append(" and so on ")
                   .append(number)
                   .append(".")
                   .toString());

java.text.MessageFormat

System.out.println(MessageFormat.format("I like {0} and I eat {1} blah blah    prolonging this string because {2} and so on {3}.",
                   cake, cakeNumber, whyNot, number));

I kind of like it with a static import, like this:

import static java.text.MessageFormat.format;

System.out.println(format("I like {0} and I eat {1} blah blah    prolonging this string because {2} and so on {3}.",
                   cake, cakeNumber, whyNot, number));

java.util.Formatter (also known as String.format)

System.out.printf("I like %s and I eat %d blah blah    prolonging this string because %s and so on %f.%n",
                  cake, cakeNumber, whyNot, number);
                  

You have lots of syntactic choice at your disposal here (Just to list some, there is probably more):

System.out.format(...)
System.out.printf(...)
System.out.print(String.format(...)) // you will need to include the line break in the format
System.out.println(String.format(...)) // line break will be caused by println()
import static java.lang.String.format;
System.out.print(format(...))
System.out.println(format(...))
System.out.println(new Formatter().format(...))

%n represents the system's specific line break character. It is required because printf does not insert a line break after the operation automatically.


Multiline string concatenation

System.out.println("I like " + cake + " and I eat " +
                   cakeNumber + " blah blah    prolonging this string because" +
                   whyNot + " and so on " + number + ".");
Answer from randers on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › tutorial › java › data › numberformat.html
Formatting Numeric Print Output (The Java™ Tutorials > Learning the Java Language > Numbers and Strings)
There are many converters, flags, and specifiers, which are documented in java.util.Formatter ... The %d specifies that the single variable is a decimal integer. The %n is a platform-independent newline character. The output is: ... The printf and format methods are overloaded. Each has a version with the following syntax: public PrintStream format(Locale l, String format, Object...
🌐
W3Schools
w3schools.com › java › ref_string_format.asp
Java String format() Method
Strings Concatenation Numbers and Strings Special Characters Code Challenge Java Math Java Booleans
Discussions

Java - String Formatting
Go look at the documentation for String.format. It doesn't just take Strings as parameters. More on reddit.com
🌐 r/learnprogramming
2
1
November 14, 2018
Should I use Java's String.format() if performance is important? - Stack Overflow
Things stayed like that for a long time until Java introduced the magic of invokedynamic and StringConcatFactory in Java 9 which does ... something I really don't even understand. But basically it "makes + faster". And boy does it. I've adapted Adam Stelmaszczyk's JMH benchmark to include an explicit StringBuilder-based test and then compared string concat (+) to String.format... More on stackoverflow.com
🌐 stackoverflow.com
[Java] How can I convert a string of long text into IPA?
Transcribing into IPA is difficult for a number of reasons. For example, which level of transcription are you after? Are you looking for the realized sounds or are you looking for the phonemes of the language? How are you planning on using this? How would you like to handle simple variations (such as the two possible vowel qualities in “the”)? How would you like to handle speaker errors? Etc. More on reddit.com
🌐 r/LanguageTechnology
6
1
November 28, 2018
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
Top answer
1 of 6
6

java.lang.StringBuilder

System.out.println(new StringBuilder("I like")
                   .append(cake)
                   .append(" and I eat ")
                   .append(cakeNumber)
                   .append(" blah blah     prolonging this string because ")
                   .append(whyNot)
                   .append(" and so on ")
                   .append(number)
                   .append(".")
                   .toString());

java.text.MessageFormat

System.out.println(MessageFormat.format("I like {0} and I eat {1} blah blah    prolonging this string because {2} and so on {3}.",
                   cake, cakeNumber, whyNot, number));

I kind of like it with a static import, like this:

import static java.text.MessageFormat.format;

System.out.println(format("I like {0} and I eat {1} blah blah    prolonging this string because {2} and so on {3}.",
                   cake, cakeNumber, whyNot, number));

java.util.Formatter (also known as String.format)

System.out.printf("I like %s and I eat %d blah blah    prolonging this string because %s and so on %f.%n",
                  cake, cakeNumber, whyNot, number);
                  

You have lots of syntactic choice at your disposal here (Just to list some, there is probably more):

System.out.format(...)
System.out.printf(...)
System.out.print(String.format(...)) // you will need to include the line break in the format
System.out.println(String.format(...)) // line break will be caused by println()
import static java.lang.String.format;
System.out.print(format(...))
System.out.println(format(...))
System.out.println(new Formatter().format(...))

%n represents the system's specific line break character. It is required because printf does not insert a line break after the operation automatically.


Multiline string concatenation

System.out.println("I like " + cake + " and I eat " +
                   cakeNumber + " blah blah    prolonging this string because" +
                   whyNot + " and so on " + number + ".");
2 of 6
2

Try printf

For example, you could write

System.out.printf("I like %s and I eat %d blah blah     prolonging this string because %s and so on %0.f.\n", cake, cakenumber, whyNot, number);

Also note that many IDEs (like Eclipse) will allow you to easily span strings across many lines. But the advantage of printf is that you separate the string from the variables, and also allows for better control over the display of numbers. For example, notice the %.0f. In general you can specify how much space the value should take up including padding and how many decimal places to use.

🌐
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 in Java 25
Learn how to format Java int, long, short and byte values with %d format specifiers, String.formatted and Java 25's IO class for clean console output.
Published: October 15, 2025
🌐
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.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Formatter.html
Formatter (Java Platform SE 8 )
July 21, 2026 - All flags defined for Byte, Short, Integer, and Long apply. If the '#' flag is given, then the decimal separator will always be present. If no flags are given the default formatting is as follows: ... The width is the minimum number of characters to be written to the output. This includes any signs, digits, grouping separators, decimal separators, exponential symbol, radix indicator, parentheses, and strings ...
Find elsewhere
🌐
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 - Supports formatting of numbers, strings, dates, and other data types. Uses format specifiers such as %s, %d, %f, and %c. Example: Java program to demonstrate working of format() method
🌐
Kansas State University
textbooks.cs.ksu.edu › cc210 › 09-strings › 06-java › 04-formatting
String Formatting :: CC 210 Textbook
3 weeks ago - For now, just remember that we’ll use String.format() whenever we want to use this method. Inside of the method, the first input is the string that contains the placeholders. In this case, we are using three different placeholders: %s - This placeholder can be replaced by any string, or any variable which can be converted to a string. %d - This placeholder can be replaced by any integer data type, including int, short, byte, or long.
🌐
Better Programming
betterprogramming.pub › ways-to-java-string-formatting-d0aecc391cc9
3 Ways To Perform Java String Formatting | by Deddy Tandean | Better Programming
March 23, 2021 - 3 Ways To Perform Java String Formatting Generate pretty strings using printf(), format(), and Formatter class Since I learned Java as one of my first object-oriented programming languages, one would …
🌐
Quora
quora.com › What-is-the-best-way-to-format-long-strings-in-Java
What is the best way to format long strings in Java? - Quora
Answer (1 of 2): As you asked about “format” I guess you want to output none-string data-types inside some sentence. You have already good answers about “String.format” (or the class java.util.Formatter behind it). Check the documentation, there are a lot of format-modifiers that can ...
🌐
Reddit
reddit.com › r/learnprogramming › java - string formatting
r/learnprogramming on Reddit: Java - String Formatting
November 14, 2018 -

/**

* Call String.format with three integer arguments and

* display them in reverse order.

* @param num1 50

* @param num2 60

* @param num3 70

* @param num4 80

*

* Output:

* Fourth: 50

* Third: 60

* Second: 70

* First: 80

*/

public static void reverseNums(add a parameter list here){ //#1

String reverse = String.format(add a format string here);	//#2

System.out.println(reverse);

}

We are supposed to reverse these numbers, however my question is how is it possible to pass the numbers as arguments into the String.format() method, can't I only pass in Strings? A nudge in the right direction would be a huge help. Thanks

🌐
Coderanch
coderanch.com › t › 623115 › java › java-String-format
Using java String.format() [Solved] (Beginning Java forum at Coderanch)
November 4, 2013 - This is my code for the string: This is my current output and my format string is: String format = "%-4s %-20s d"; (I used the 0's to keep track of where the itemName Ends) Based on this tutorial, -4s would mean that my itemNumber takes up 4 spaces and will be left justified, then my itemName will take up 20 spaces and would be left justified, then 04d would right justify my itemValue and pad it with 0's to the left if the value does not take up 4 character spaces.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › java string format
The Power of Java String Format: Harnessing the Full Potential of String Manipulation
July 4, 2026 - You will learn how to setup the coding environment, I/O Model, various modules and packages, JSON & JavaScript objects. ... Talk to our experts. We are available 7 days a week, 10 AM to 7 PM ... String formatting is used in Java applications for clean, readable, and well-structured output.
🌐
TheServerSide
theserverside.com › blog › Coffee-Talk-Java-News-Stories-and-Opinions › long-to-String-in-Java
How to convert a long to a String in Java 25
Use DecimalFormat when you actually need numeric formatting rules rather than a basic conversion. Here’s a JShell script you can run that demonstrates the five approaches to the long to String conversion problem listed above: // Modern ways to convert a long to String in Java 25 long value = 90210L; String a = Long.toString(value); String b = String.valueOf(value); String c = "%d".formatted(value); String d = "" + value; String e = new java.text.DecimalFormat("#").format(value); IO.println(a); IO.println(b); IO.println(c); IO.println(d); IO.println(e);
Published: August 8, 2025
🌐
Swagger
swagger.io › specification
OpenAPI Specification - Version 3.2 | Swagger
Many frameworks define query string syntax for complex values, such as appending array indices to parameter names or indicating multiple levels of of nested objects, which go well beyond the capabilities of the deepObject style. As these are not standards, and often contradict each other, the OAS does not attempt to support them directly. Two avenues are available for supporting such formats with in: "querystring":
🌐
Dumb IT Dude
dumbitdude.com › home › string format java | formatting a string | date time format specifiers
String Format Java | Formatting a String | Date Time Format Specifiers
June 20, 2017 - Now comes the part where you learn how to use a format specifier. There are three ways to achieve that in Java: ... It is one of the most sought after ways of string format Java. The String class has a format() method in it which helps in formatting a string.
Top answer
1 of 14
269

I took hhafez's code and added a memory test:

private static void test() {
    Runtime runtime = Runtime.getRuntime();
    long memory;
    ...
    memory = runtime.freeMemory();
    // for loop code
    memory = memory-runtime.freeMemory();

I run this separately for each approach, the '+' operator, String.format and StringBuilder (calling toString()), so the memory used will not be affected by other approaches. I added more concatenations, making the string as "Blah" + i + "Blah"+ i +"Blah" + i + "Blah".

The result are as follows (average of 5 runs each):

Approach Time(ms) Memory allocated (long)
+ operator 747 320,504
String.format 16484 373,312
StringBuilder 769 57,344

We can see that String + and StringBuilder are practically identical time-wise, but StringBuilder is much more efficient in memory use. This is very important when we have many log calls (or any other statements involving strings) in a time interval short enough so the Garbage Collector won't get to clean the many string instances resulting of the + operator.

And a note, BTW, don't forget to check the logging level before constructing the message.

Conclusions:

  1. I'll keep on using StringBuilder.
  2. I have too much time or too little life.
2 of 14
136

I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self

import java.io.*;
import java.util.Date;

public class StringTest{

    public static void main( String[] args ){
    int i = 0;
    long prev_time = System.currentTimeMillis();
    long time;

    for( i = 0; i< 100000; i++){
        String s = "Blah" + i + "Blah";
    }
    time = System.currentTimeMillis() - prev_time;

    System.out.println("Time after for loop " + time);

    prev_time = System.currentTimeMillis();
    for( i = 0; i<100000; i++){
        String s = String.format("Blah %d Blah", i);
    }
    time = System.currentTimeMillis() - prev_time;
    System.out.println("Time after for loop " + time);

    }
}

Running the above for different N shows that both behave linearly, but String.format is 5-30 times slower.

The reason is that in the current implementation String.format first parses the input with regular expressions and then fills in the parameters. Concatenation with plus, on the other hand, gets optimized by javac (not by the JIT) and uses StringBuilder.append directly.

🌐
DigitalOcean
digitalocean.com › community › tutorials › java-long-to-string
Java long to String | DigitalOcean
August 3, 2022 - Technical tutorials, Q&A, events — This is an inclusive place where developers can find or lend support and discover new ways to contribute to the community.
🌐
MongoDB
mongodb.com › docs › atlas › troubleshoot-connection
Troubleshoot Connection Issues - Atlas - MongoDB Docs
Java (Sync) Node.js · Python · Do not encode special characters in your password if you are using your password outside of a connection string URI (for example, pasting it into mongosh). If you see this error message, your driver is likely out of date. For instructions on updating your driver, refer to your specific Driver Documentation. When you use the DNS seed list connection string format to connect to Atlas, you might see the following error: This error may occur when using the default DNS server that your ISP provides.