Friday, August 15, 2008

Java is Pass By Value !!

Although most books on Java(except a few good ones) will beg to differ and say that "In Java, primitives are passed by value and objects by references"
But, this is not true. Or you can say that it is 50% true.
Because, even Objects when passed as parameters to a method are passed by value !!
Hard to Digest !!
But it is TRUE. This is not to say that changes are not reflected back when objects are passed to a method.

Actually what happens when you try and pass an object as a parameter is that the bit representation of the actual parameter(lets say the address of the actual object on the heap) is COPIED to the formal parameter. So at this time both references are pointing to the same object on the heap and thus any changes made to it are reflected back in the calling code.
A proficient C programmer is not akin to this concept as it works in C exactly the same way.

Try out the following program to understand how parameter passing works in Java.

class myClass
{
int val;

myClass(int x)
{
val = x;
}
void display()
{
System.out.println(" Value is "+val);
}
}

class test
{
static void modifyValue(myClass o)
{
o = new myClass(20);
o.display();
}

public static void main(String[] args)
{
myClass ob = new myClass(10);
ob.display();
modifyValue(ob);
ob.display();
}
}


The output is
Value is 10
Value is 20
Value is 10

Third line says that the value of object ob has not changed after passing it to a method and making changes there.
This happened because objects ob and o are different entities and changing o (the reference) bit pattern (the address) by creating a new object won't affect ob in any way.

The bottom line on pass-by-value : Java is actually pass-by-value for all variables running within a single VM(virtual machine).

Notes:
Exception to this rule is perhaps :
1. Parmeter passing in RMI (Remote Method Invocation)

Comments & Corrections are Welcome. :-)

No comments: