Saturday, 21 November 2015

Java is Pass by Value or Pass by Reference !!!!


In the Java , there is no concept of pointers and objects are  stated to have passed by value. In case of primitives only values can be passed to a method and in case of java objects , it is said to be pass by reference value.

I think correct term should be termed as  Pass by reference value instead of Pass by Value.

Behind the scene its the passing of the value of the reference bit by bit in the method  so its not passing the reference. Following example would validate the  above facts  :


public class Name
{
String name;

Name(String name){
this.name = name;
}

public static void changeNameReference(Name oldname){
oldname = new Name("John");
}
public static void modifyNameReference(Name oldname){
oldname.name = "Brock";
}

public static void main (String[] args) throws java.lang.Exception
{
Name newname = new Name("Rock");
System.out.println("#1.Original name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));
changeNameReference(newname);
System.out.println("#2.After changeNameReference method call name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));
modifyNameReference(newname);
System.out.println("#3.After modifyNameReference method call name= " + newname.name + " and system hashcode=" + System.identityHashCode(newname));

}

}

Output : 
-----------------------------------------------------------------------
#1.Original name= Rock and system hashcode=582216281
#2.After changeNameReference method call name= Rock and system hashcode=582216281
#3.After modifyNameReference method call name= Brock and system hashcode=582216281

------------------------------------------------------------------------

Following points by points to keep understand the above example :

1. Note the Point#1 and # 2 having the same value of the object even though object is passed into the method changeNameReference   which assigning the new reference to the object but original object remain intact.

2. In the point#3 , when a new value is assigned to the  argument object to the method  modifyNameReference , its changed the value of the original object with the  new value "Brock"

3. Value of the object is being passed bit by bit but reference remain same in the Heap memory

4. Note the system hash code value  they are same, so object reference is same  in the heap memory.If reference would have passed then definitely the value system hashcode  would have changed.

Note that Class instance and Array  are the objects in java, so passing the reference value in any method would not affect the reference of the object.


No comments:

Post a Comment