• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between String and StringBuffer.  RSS feed

 
Abhijeet Deshmukh
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,

I m totally confused about String and StringBuffer. What is String and StringBuffer Pools, how they work ?



which must be used in what situations. how can it be used to improve performance.




regards and thanks in adv,
abhijit
 
Joe Ess
Bartender
Posts: 9429
12
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Java Tutorial: Strings and String Buffers
 
Ganesh Gowtham
Ranch Hand
Posts: 225
IBM DB2 Eclipse IDE Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
Since String is the immutabble object each and very thing u manuplate on that it will create a memory then it wont be free'd
for example
String str = "a"; line 1
str = str + "b"; line 2
str = str + "c"; line 3

Obviously ur o/p is abc when u think in the performance side ,
in the line 2 it will create another memory space after the reassigning the "str" , there by there is no reference to object created in line 1.
Thanks
 
devaiah
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do you mean like this..

String str = "HELLO";
It create one memory location for str variable and one "HELLO" String in stringPool.

where as String Str1="H"+"E"+"L"+"L"+"0";

for str1..its create 1 memory location and string pool contain different strings
like H,E,L,O, and HE,HEL,HELL,HELLO ?..

please tell me wether my understanding is correct or not?..

&

what is the difference of Str1="H"+"E"+"L"+"L"+"0";
and
Str1="H";
Str1 = Str1+"E";
Str1 = Str1+"L";
Str1 = Str1+"L";
Str1 = Str1+"O";

??
 
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

where as String Str1="H"+"E"+"L"+"L"+"0";

for str1..its create 1 memory location and string pool contain different strings
like H,E,L,O, and HE,HEL,HELL,HELLO ?..


If my name was 'compiler', aka 'javac', I would optimize

and to see what your javac is doing, you may generate two source-files, compile them and compare them by hex.

But if the parts to be combined are only known at runtime, your idea is right - a lot of intermediate Strings might be created.

I'm not sure, how dynamic optimization is reducing this overhead in which circumstances - if you're sure, the code is only called a few times, and isn't run in performance-critical situations, String-catenation is ok.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!