Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using + to concat string in Java

I have a huge string as below :

String str = "aaaaaaa" 
        + "bbbbbbbb" 
        + "cccccccc" 
    .... 

        + "zzzzzzzz";  // about 200 lines long

Is it a big waste of memory? Will it be better to put it in one line or use StringBuilder? This is done to create a long sql.

like image 291
fastcodejava Avatar asked Apr 25 '13 16:04

fastcodejava


People also ask

What is concat () Java?

Java - String concat() Method This method appends one String to the end of another. The method returns a String with the value of the String passed into the method, appended to the end of the String, used to invoke this method.

Can you use += with strings in Java?

In Java, two strings can be concatenated by using the + or += operator, or through the concat() method, defined in the java. lang. String class.

Can we use concat in string?

You can only pass a String to the concat() method. If one of the operands is a string and another is a non-string value. The non-string value is internally converted to a string before concatenation.


2 Answers

No. The compiler will perform the concatenation at compile time if all your strings are constant (as they are in your question). So that ends up performing better than the StringBuilder version.

It will use StringBuilder (or StringBuffer) to perform the concatenation of any non-constant parts otherwise.

So the compiled version of:

String x = "a" + "b";

should be exactly the same as:

String x = "ab";

Note that the "non-constant" parts can mean that you can sometimes get (very minor) extra efficiencies using bracketing wisely. For example:

int value = ...;
String x = "a" + value + "b" + "c";

... is less efficient than:

int value = ...;
String x = "a" + value + ("b" + "c");

... as the first appends "b" and "c" separately. The efficient version is equivalent tO:

int value = ...;
String x = "a" + value + "bc";

I can't remember ever seeing this used as a legitimate micro-optimization, but it's at least a point of interest.

like image 152
Jon Skeet Avatar answered Oct 10 '22 19:10

Jon Skeet


In current versions of Java, each + (concatenation) operation gets automatically compiled to a StringBuilder append() operation. However, if it's inside a loop, it will create a new StringBuilder for each iteration, negating its effect - so you'd be better of managing the StringBuilder explicitly.

like image 32
Óscar López Avatar answered Oct 10 '22 18:10

Óscar López