• 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
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

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:

 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic