Thursday, April 24, 2008

Java - No Pass by Reference

Back to Basics :)

I still see some of my friends get confused with Pass by Reference in Java. Only point to note, there is no pass by reference in Java, we only have pass by Value and sometime we pass the object reference by Value(that doesn't mean pass by Reference).
Year back I had a big discussion on my Orkut community about this and I am again posting the same code for clearing the confusion.

class MyClass {
String name;
int nameCode;

public MyClass(String name, int nameCode) { = name;
this.nameCode = nameCode;
public String toString() {
System.out.println(name + " : " + nameCode);
public class NoCallByReference {
public static void swap(MyClass a, MyClass b) {
MyClass temp = a;
a = b;
b = temp;
public static void main(String[] args) {
MyClass myclass = new MyClass("Ramu", 7);
MyClass yourclass = new MyClass("Mohan", 1);
swap(myclass, yourclass);

A very simple code where I tried to swap two object of myClass. But you will surprise to see the output because after swapping even the value of myclass and yourclass will remain the same. Because the copy of myclass and yourclass has been created and get swapped rather than actual myclass and yourclass. It's like

myclass --- copyofmyclass
yourclass --- copyofyourclass

Swapping is done on copyofmyclass and copyofyourclass. Better to go for a homework and run the command

javap -c NoCallByReference and try to figure our how assemble is going on :-).

For more details and hot talk check the orkut link here.


Rajesh Balamohan said...

There is nothing wrong in the behaviour of this code.

May be this link will help

References are copied and not the objects. So its always pass-by-value

Vaibhav said...

Thanks Rajesh ! Same I also mentioned :)

jegadeesh said...

Thank I dont no how to use pass by reference but ur code help me how to use it.....
thank u

Vaibhav said...

no pass by reference in Java. I guess this is what you are going to use :)