• Post Reply Bookmark Topic Watch Topic
  • New Topic

How “String” concatenation uses “StringBuilder/StringBuffer” internally?  RSS feed

 
Gajendra Tomer
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi There,

Can we say that following expression:

String output="str1"+"str2"+"str3"+"str4"+"str5"+2

Is equivalent to once compiled by javac:

String output=new StringBuffer("str1").append("str2").append("str3").append("str4").append("str5").append("2") .toString() ?

Thanks,
Gajendra
 
Henry Wong
author
Sheriff
Posts: 23295
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Gajendra Tomer wrote:
Can we say that following expression:

String output="str1"+"str2"+"str3"+"str4"+"str5"+2

Is equivalent to once compiled by javac:

String output=new StringBuffer("str1").append("str2").append("str3").append("str4").append("str5").append("2") .toString() ?


A couple of points.

1. The StringBuffer/StringBuilder class has support to append() an int, so the compiler don't need to append a "2" string. It can append the int.

2. The compiler handles compile time constants at ... well, compile time. In your example, you have a compile time constant expression, so it will be the equivalent to ...

String output="str1str2str3str4str52";


Regardless, to answer your question.... yes, in an example where it isn't a compile time constant, what you describe is essentially correct.

Henry
 
Campbell Ritchie
Marshal
Posts: 56598
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
. . . at present. That might change in future. Try this little class, which you must execute with three command*#x2011;line arguments, like thisThe character corresponding to 0x20 is space.
the javap call will allow you see the inner workings of the bytecode, and you can verify from that whether it uses a StringBuilder. Presumably Java1.4 and older versions used a StringBuffer.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!