• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

StringBuffer

 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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)
 
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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:

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic