Java is Pass by Value. Period.
Java is Pass by Value
Ok. I don't blog on technincal things here. As a change I am presenting this heavily misuderstood topic. Have a look at the article here and the accompanying terse diagram here.
- Java is pass by value
- Java is pass by value
- Java is pass by value
He has this program:
public class SwapObject {
private int value = -1;
public SwapObject(int i) {
value = i;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public static void swap(SwapObject a, SwapObject b) {
int t = a.value;
a.value = b.value;
b.value = t;
}
public static void main(String[] args) {
SwapObject a = new SwapObject(1),
b = new SwapObject(2);
System.out.println("a = " + a.getValue() + ", b = " + b.getValue());
SwapObject.swap(a, b);
System.out.println("a = " + a.getValue() + ", b = " + b.getValue());
}
}
which gives the output:
a = 1, b = 2 a = 2, b = 1
Well Shyam, what you are doing is you are changing the value using the <strong> copy of reference</strong>. True that Java is pass by value, but that's half truth. It's pass by value of reference.
It's possible to change the original object using the reference and that's what you are witnessing.
--praneet
Posted by Praneet Tiwari on July 17, 2006 at 04:07 PM TPT #
Posted by Bruce on February 02, 2007 at 08:08 AM TPT #
Posted by bhattathiri on June 17, 2007 at 12:49 PM TPT #