File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes StringBuffer Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "StringBuffer" Watch "StringBuffer" New topic


Netty poestel
Ranch Hand

Joined: Sep 20, 2004
Posts: 131

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's only 'sb' that's bothering)
Seema Manivannan
Ranch Hand

Joined: Sep 20, 2001
Posts: 128
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"


Seema Manivannan<br />Author and Trainer: Java Certifications<br /> <br />Whizlabs Software<br />Success, certified!<br />Global leader: J2EE certification exam preparation!<br /><a href="" target="_blank" rel="nofollow"></a><br /> <br />An ISO 9001-2000 certified company!
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
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:

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
I agree. Here's the link:
subject: StringBuffer
It's not a secret anymore!