Klook.com
jasa pembuatan repository kampus

Is Call by Reference Possible in Java?

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

About the Author: admin

Kangdadang earned his Diploma degree from dr Otten Academy of Nursing, Bandung in 2002. 2010 He joined the accounting graduate program In economics faculty at The University of Kepulauan Riau. He received his Master of Science degree in Human Resource in 2013 from The University of Batam. While his work at local government, Kang Dadang also interest on IM, today he manage many blog and owner of Pesonaweb.com
%d bloggers like this: