String.format() vs "+" operator

41,666

Solution 1

If you are looking for performance only I believe that using StringBuilder/StringBuffer is the most efficient way to build strings. Even if the Java compiler is smart enough to translate most of String concatenations to StringBuilder equivalent.

If you are looking for readability the String.format thing is the much clearer I think, and this is what I use also unless I need to rely on high performance.

So if your main concern is not performance, meaning this code is not in a path that is called a lot, you may prefer to use String.format as it gives a better idea of the resulting String (like you said).

Besides, using String.format lets you use the format thing, which means you can use it for padding Strings, formatting numbers, dates, and so on, which would make the code even worse if using simple concatenation.

Edit for Chuu:

Using JAD, you can see that the following code:

public class Test {
    public static void main(String[] args) {
        String str = "a" + "b" + "c";
        String str2 = "foo" + str + "bar" + str;
        System.out.println(str2);
    }
}

when decompiled will look like:

public class Test {
    public static void main(String[] args) {
        String str = "abc";
        String str2 = new StringBuilder("foo").append(str).append("bar").append(str).toString();
        System.out.println(str2);
    }
}

Proof of that can also be found using the javap utility that will show you the Java bytecode under a .class file:

public static void main(java.lang.String[] args);
    0  ldc <String "abc"> [16]
    2  astore_1 [str]
    3  new java.lang.StringBuilder [18]
    6  dup
    7  ldc <String "foo"> [20]
    9  invokespecial java.lang.StringBuilder(java.lang.String) [22]
   12  aload_1 [str]
   13  invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [25]
   16  ldc <String "bar"> [29]
   18  invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [25]
   21  aload_1 [str]
   22  invokevirtual java.lang.StringBuilder.append(java.lang.String) : java.lang.StringBuilder [25]
   25  invokevirtual java.lang.StringBuilder.toString() : java.lang.String [31]
   28  astore_2 [str2]
   29  getstatic java.lang.System.out : java.io.PrintStream [35]
   32  aload_2 [str2]
   33  invokevirtual java.io.PrintStream.println(java.lang.String) : void [41]
   36  return

Solution 2

What should be used for a basic string concatenation operation ?

The examples you provide serves different purposes. + is overloaded to concat Strings but String.format is used to format strings, as name specifies.

Concatenating strings together is not it's primary job.

So, if the requirement is just to concatenate use + or concat method.

These links will be useful:

Should I use Java's String.format() if performance is important?

Is it better practice to use String.format over string Concatenation in Java?

Solution 3

Try this

    long t0 = System.currentTimeMillis();
        String userName = "test";
        for (int i = 0; i < 1000000; i++) {
            String randomString = "hello " + userName + " how are you?";
//          String randomString = String.format("hello %s how are you ?",userName);
        }
        System.out.println(System.currentTimeMillis() - t0);

you will be surprised to know that concatination is 10 times faster that String.format. But format can do a lot of extremely useful things with numbers, dates, etc. See java.util.Formatter API, which is actually used by String.format, for details.

Solution 4

My two cents: always use String.format()

Internationalisation is a much bigger concern than style or performance in this situation. For that reason I would always use String.format()

English text: "Hello " + userName + " how are you?"

Translation into Jedi: userName + "you are how? Hello!"

If the strings are concatenated, changing word order can be difficult if not impossible for the translator. This problem becomes increasingly worse as there are more pieces to the string and more placeholders.

Solution 5

In my opinion, use + operator.

If performance is a concern you should be using StringBuilder and as Alex pointed out in his comment above, the Java compiler will convert:

String str2 = "a" + str1;

to: String str2 = new StringBuilder("a").append(str1)).toString();

In addition to this you can avoid runtime exceptions by using the + operator. Instead you'll get syntax errors that you can catch at compile time. For example:

    String var = "huge success.";

    System.out.print( "I'm making a note here: " + var );
    //System.out.print( "Printing: " + ); Syntax error!

    System.out.print( String.format( "I'm making a note here: '%s'", var ) );
    System.out.print( String.format( "I'm making a note here: '%s'" ) ); // runtime exception!
    System.out.print( String.format( "I'm making a note here: '%d'", var ) ); // runtime exception!

Readability comes down to personal preference. However I will say that the String.format syntax is basically from C++ and most language created since then have embraced the + operator for readability reasons.

Share:
41,666
Priyank Doshi
Author by

Priyank Doshi

I am a software development engineer at Amazon. Language: java c/c++ html , css , jquery Frameworks: Spring core &amp; MVC Hibernate

Updated on July 30, 2020

Comments

  • Priyank Doshi
    Priyank Doshi almost 4 years

    What should be used for a basic string concatenation operation ?

    String randomString = "hello " + userName + " how are you" ?
    

    or

    String randomString = String.format("hello %s how are you ?",userName);
    

    I feel String.format() gives a better idea of output string. But what are actually pro and cons in using any of one ?

    Is there anything in terms of performance or orphan entries in string literal pool.

    Edit : I am talking about multiple parameters in string, not just one. Around 5 +.

    Bonus Question : Please also share your view on which one should actually use ? any one of these or 3rd one... !! ?