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

StringBuffer

 
Netty poestel
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


I must admit I was schocked when sb=null[I had bet my money here] was actually sb=bbbaaabbb in the final output.
why setting the local reference of sb (in method testRefs()) to null, does not affect sb . ....?
**PS( b.t.w output of 's' is all fine......it's only 'sb' that's bothering)
 
Seema Manivannan
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you pass an object reference to a method, only the copy of the reference variable is passed. Then both the variable and its copy refer to the same object. So both the variables - sb in the main method and sb in the testRef method - refer to the same StringBuffer object. So the object can be modified by using either of these variables.

However, making the variable sb in the testRef method refer to null, will not affect the variable sb in the main method. It will still refer to the same StringBuffer object itself which now contains the value "bbbaaabbb"

Thanks,
Seema
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Following on from Seema says, if you change the name of the parameter in method testRefs from sb to aStringBuffer, and change all of the usages of sb in the body of method testRefs to aStringBuffer, then you will see clearer what is going on:

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic