Thursday, September 15, 2005

call by value v/s call by reference

public class StrBufTest {

public void method1(StringBuffer s1, StringBuffer s2) {

s1.append("There");

s2 = s1; //line 4

}

public static void main(String args[]) {

StringBuffer sb1 = new StringBuffer("Hello");

StringBuffer sb2 = new StringBuffer("Hello");

StrBufTest sbt = new StrBufTest();

sbt.method1(sb1, sb2);

System.out.println("sb1 is " + sb1 + "\nsb2 is " + sb2);

}

}


The Answer to the above question is

sb1 is "Hello There"

sb2 is "Hello".


I can't understand exactly why the value of sb2 is "Hello" and not "Hello There" since at line 4 s2 references the same object as s1. My question is are objects passed by reference. If they are then sb2 should be "Hello There". If they r passed by value then the answer is justified. I am confused because I have read Khalid's book and it mentions that objects are passed by reference.


The object is passed by reference, but the object reference variable is passed by value. When you pass an object reference variable to a function, you can potentially change the state of the object, but you can't make the passed reference variable refer to another object.


"The parameter passing strategy in Java is call-by-value and not call-by-reference, regardless of the type of the parameter"




0 Comments:

Post a Comment

<< Home