Programming codex

Is Call by Reference Possible in Java?

Is Call by Reference Possible in Java?

[ad_1]

It is often asked if call by reference is possible in java? People confuse so frequently with this simple and basic concept that it is hard to believe.

Let me try to answer that question by taking an example. But first, the basics. 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 objects of myClass. But you will surprise to see the output because after swapping even the value of my class and your class will remain the same. Because of the copy of my class and your class has been created and get swapped rather than actual my class and your class. It’s like

my class – a copy of my class

your class – copy of your class

Swapping is done on a copy of my class and a copy of your class. Better to go for homework and run the command

javac NoCallByReference and try to figure out how assemble is going on :-).

[ad_2]

Source by Vaibhav Kumar Choudhary

Share on facebook
Share on google
Share on twitter
Share on linkedin
Share on pinterest
Share on whatsapp

Leave a Reply

Your email address will not be published. Required fields are marked *

Search:

Topics

Recent Posts