File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes How “String” concatenation uses “StringBuilder/StringBuffer” internally? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How “String” concatenation uses “StringBuilder/StringBuffer” internally?" Watch "How “String” concatenation uses “StringBuilder/StringBuffer” internally?" New topic
Author

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

Gajendra Tomer
Ranch Hand

Joined: Sep 22, 2008
Posts: 32
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

Joined: Sep 28, 2004
Posts: 18717
    
  40

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

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38363
    
  23
. . . 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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How “String” concatenation uses “StringBuilder/StringBuffer” internally?