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… !! ?
If you are looking for performance only I believe that using
StringBuilder/StringBufferis the most efficient way to build strings. Even if the Java compiler is smart enough to translate most of String concatenations toStringBuilderequivalent.If you are looking for readability the
String.formatthing 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.formatas it gives a better idea of the resulting String (like you said).Besides, using
String.formatlets 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:
when decompiled will look like:
Proof of that can also be found using the
javaputility that will show you the Java bytecode under a.classfile: