Deprecated: Assigning the return value of new by reference is deprecated in /home/w3hja33/public_html/wp-includes/cache.php on line 99

Deprecated: Assigning the return value of new by reference is deprecated in /home/w3hja33/public_html/wp-includes/query.php on line 21

Deprecated: Assigning the return value of new by reference is deprecated in /home/w3hja33/public_html/wp-includes/theme.php on line 576
Javac | w3hJava

w3hJava

What, Why, When and How of Java, JavaFX and related technologies


Published May 23rd, 2008

Java - Pass by Reference(Not possible)

I had a big time fight on my Orkut community with the concept that Java do things with Pass by Reference. Here is the one for Orkut users :

Here

But for non-orkut users let me recap the point again, its very important for a person who is new in java:

There is NO CONCEPT OF CALL BY REFERENCE IN JAVA, ONLY CALL BY VALUE IS POSSIBLE. We generally get confused in pass the object reference by value and passing by reference. Both are completely different.

Here is a small code, to get a more clear picture:

class MyClass {

String name;
int nameCode;

public MyClass(String name, int nameCode) {
this.name = name;
this.nameCode = nameCode;
}

public String toString() {
System.out.println(name + " : " + nameCode);
return (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);
myclass.toString();
yourclass.toString();
}
}

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 :-).