Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the diff b/w string & String buffer?

 
mara thamizhan
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
I am a newbie to java programming.

I want to know the difference between using String & StringBuffer classes.

I read that String is fixed length character sequence,whereas StringBuffer is varied length character sequence!

plz explain!

cheers!
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read that String is fixed length character sequence,whereas StringBuffer is varied length character sequence!


Well, rather than saying "fixed length", we say immutable. Which means that once you've set its value, you cannot change it anymore.

String mystring = "a";
mystring = mystring + "b";

You think that you are using the same String variable, but in fact, JVM create a new one. You'll usually use StringBuffer to concatenate Strings. This avoids creating of new strings each time.
 
Amit Ghai
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an extract from the javadoc over String class. - Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.
 
Rusty Shackleford
Ranch Hand
Posts: 490
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"You think that you are using the same String variable, but in fact, JVM create a new one."

replace variable with object
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic