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

Comments:

Shyam came up with a doubt.
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 #

I'm not sure the average programmer is interested in the technical differences between Java and C's copying of pointers (or not). When a programmer asks whether something is passed by value or reference, he wants to know whether the object is mutable. He doesn't care whether or not there is one copy of the reference pointer or two. You say this is a misunderstood topic but I don't see how saying "Java is pass by value" or "Java is pass by value of reference" improves understanding.

Posted by Bruce on February 02, 2007 at 08:08 AM TPT #

In the storm of life we struggle through myriads of stimuli of pressure, stress, and muti-problems that seek for a solution and answer. We are so suppressed by the routine of this every life style that most of us seem helpless. However, if we look closely to ancient techniques we shall discover the magnificent way to understand and realize the ones around us and mostly ourselves. If only we could stop for a moment and allow this to happen.

Posted by bhattathiri on June 17, 2007 at 12:49 PM TPT #

Post a Comment:
  • HTML Syntax: NOT allowed

This blog copyright 2009 by praneet