Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Diff between string and string buffer

 
Jethram Boda
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Diff between string and string buffer
 
Ulf Dittmer
Rancher
Pie
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.

The javadocs for String and StringBuffer do not look very much alike, indicating that they are quite different. In what way do you perceive them as being alike?
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Biggest difference:

String is immutable; every method that returns a string returns a new object.
StringBuffer (and StringBuilder in Java5 and up) is mutable; (nearly) every method changes the object itself, and the object itself is returned.


However, as Ulf said, they are very unsimilar. The better question would be: what are the similarities between String and StringBuffer?

The answer to that would be, they both implement CharSequence, so you can get access to every character of the object you want.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jethram Boda:
Diff between string and string buffer


I'm very surprised you got an answer to this question. You've posted in the wrong forum (this is not an Advanced Java question), you've used non-words ("diff"), your post is not a sentence (or a question) and you haven't even typed the Java class names properly.

You very welcome to the Ranch, but I recommend you should read HowToAskQuestionsOnJavaRanch to get the most from it.
 
Gabriel Claramunt
Ranch Hand
Posts: 375
Monad Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well... I tried "diff String.java StringBuffer.java" on my UNIX box, but the result is too long to paste here
[ September 19, 2007: Message edited by: Gabriel Claramunt ]
 
Michael Raymond Jr.
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jethram Boda:
Diff between string and string buffer


//immutable
String s1 = "s1";
s1.concat(" - s1");
//new string created. " - s1" is NOT appended to original s1 value - a
//new value is created in memory for which you have no reference to.
System.out.println(s1); //only print s1

//mutable, value can be changed
StringBuffer s2 = new StringBuffer("s2");
s2.append(" - s2");
//s2 is actually appended here with " - s2" and still
// referenced by s2 variable
System.out.println(s2); //prints "s2 - s2"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic