Which one will be better use for Concatenation of String
If i want to build a string from bunch of string variables such as str1 and str2, which one will be better one ???
String str="This the String1 " + str1 + " merged with Sting2 " + str2;
String str=String.format("This the String1 %s merged with Sting2 %s", str1 , str2);
What i think is second one will be better , because first one will suffer from creation of lot of string.
correct me if i am wrong ? and provide feedback on same
The concat() method appends (concatenate) a string to the end of another string.
concat() method takes only one argument of string and concatenates it with other string. + operator takes any number of arguments and concatenates all the strings.
There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.
The CONCAT function combines the text from multiple ranges and/or strings, but it doesn't provide delimiter or IgnoreEmpty arguments. CONCAT replaces the CONCATENATE function. However, the CONCATENATE function will stay available for compatibility with earlier versions of Excel.
The first won't actually create any extra strings. It will be compiled into something like:
String str = new StringBuilder("This the String1 ")
.append(str1)
.append(" merged with Sting2 ")
.append(str2)
.toString();
Given that the second form requires parsing of the format string, I wouldn't be surprised if the first one actually runs quicker.
However, unless you've got benchmarks to prove that this is really a bit of code which is running too slowly for you, you shouldn't be too worried about the efficiency. You should be more worried about readability. Which code do you find more readable?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With