Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String Concatenation using concat operator (+) or String.format() method

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 ???

  1. String Concat operator

String str="This the String1 " + str1 + " merged with Sting2 " + str2;

  1. String format method

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

like image 773
ajduke Avatar asked Dec 14 '11 10:12

ajduke


People also ask

What is the use of the concat () method in Java?

The concat() method appends (concatenate) a string to the end of another string.

What is difference between concat () and operator in 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.

What are the 2 methods used for string concatenation?

There are two ways to concatenate strings in Java: By + (String concatenation) operator. By concat() method.

What concat () will?

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.


1 Answers

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?

like image 196
Jon Skeet Avatar answered Oct 13 '22 22:10

Jon Skeet