Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer question

 
Serena Zhou
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Could anyone explain why this code from Dan Chisholm mock exam have the output of "ABABCABC"?

When s1 was passed to m1, shouldn't another copy of s1 be created and changed which does not affect s1 itself?
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Serena,
Java does always pass by value, making a copy and then passing it. But also remember that in Java, references to Java is what is being copied. So, the reference is copied and pass. The copy still refers to the same StringBuffer though, so both m1 and m2 alter the same StringBuffer.
 
Serena Zhou
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, Thanks!
String is immutable and StringBuffer is not.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic