0

Onward Java 5,for concatenating string we can use '+' because it internally uses string builder.Is it right. How?

example:

    String a="A";
    String b="C";
    String a=a+b;

  is same as

    StringBuilder builder=new StringBuilder("A");
    builder.append("B");

Which is efficient?why? Thank you

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Oomph Fortuity
  • 5,710
  • 10
  • 44
  • 89
  • 1
    This question has been asked many times before http://stackoverflow.com/questions/4645020/when-to-use-stringbuilder-in-java – M-Wajeeh Oct 04 '13 at 06:21

4 Answers4

1

The two are functionally the same. Meaning they perform the same task. They are quite different in how they operate behind the scenes.

String concatenation with the + operator will take marginally longer to process because of what happens when it's compiled into bytecode. Without delivering the bytecode here is the code equivalent of concatenation compiled:

// Concatenation
String a = "a";
String b = "b";

a = a + b;

// It's equivalent once it's compiled
String a = "a";
String b = "b";

StringBuilder aBuilder = new StringBuilder(a);
aBuilder.append(b);
a = aBuilder.toString();

As you can see, even though no usage of a StringBuilder is present in the concatenation snippet a StringBuilder is still created and used. This is why (mostly for large data sets where the time will be noticeable) you should avoid concatenation to avoid the need for firing up String builders like this. Just use a builder from the beginning:

StringBuilder a = new StringBuilder("a");
a.append("b");
System.out.println(a);

And you'll save yourself some execution time and memory.

Brandon Buck
  • 7,177
  • 2
  • 30
  • 51
0

You can easily do a small experiment by setting a breakpoint inside the StringBuilder and then run your program with stringA + stringB.

When I was trying on JDK later than 1.5 this seems to bring me to the breakpoint correctly. Thus I think the proper substitution is done during compile time.

Alex Suo
  • 2,977
  • 1
  • 14
  • 22
0

In string + will be used to concat the two string but it will take some time and space which is proportional to length of two strings.

The object StringBuilder has a more efficient way of concatenate Strings. It works similar to ArrayList by allocating predefined array for storing the characters and keeps track of used space. Every time space is exceeded then it will exte

abcd
  • 3,164
  • 2
  • 18
  • 13
-1

This is same, and there is not much diference, but when you concatenating more that two strings, there is more StringBuilders created. and performance can be low.

Jan Pešta
  • 644
  • 1
  • 5
  • 11