I thought the answer would be HELLOTHERE,HELLOTHERE but sb2 is still HELLOO. can anyone explain this.
public class Test{ public void method1(StringBuffer s1,StringBuffer s2){ s1.append("THERE"); s2=s1; } public static void main(String arg[]){ StringBuffer sb1=new StringBuffer("HELLO"); StringBuffer sb2=new StringBuffer("HELLOO"); Test t=new Test(); t.method1(sb1,sb2); System.out.println("sb1 is"+sb1+"sb2 is"+sb2); }} answer is HELLOTHERE,HELLOO Thanks in advance.
Sandeep Potnis
Ranch Hand
Joined: Aug 18, 2000
Posts: 39
posted
0
Santoo, This looks likes a "passing a reference by value" issue. Try to re-think the question on those lines. Sandeep
robl
Greenhorn
Joined: Aug 26, 2000
Posts: 25
posted
0
Originally posted by Sandeep Potnis: Santoo, This looks likes a "passing a reference by value" issue. Try to re-think the question on those lines. Sandeep
I believe that is correct. When you pass an object as a parameter, you are passing a reference(actually a copy of the reference) and you can not effect the contents of the object without invoking a method. s2 = s1 simple changes the reference locally and does not effect the reference of the calling method. I hope that makes sense. Maybe somebody else can explain it better.