Saturday, July 12, 2014

Is Java “pass-by-reference” or “pass-by-value”?

Java is always pass-by-value. !!!!

However there is a difficulty in understanding this or more over a confusion when we are dealing with method calls involving Java Objects.

Java Specification says that everything in Java is pass-by-value and there is nothing called "pass-by-reference" in Java. To understand more about this, we can start with Java Object and reference understanding. Say we have a class called Employee

public class Employee
{
     private int id;
     private int age;
     private String name;

    // Getters-Setters ...

}

Now we will create an object instance of Employee as below

    Employee myEmp = new Employee();

Here myEmp is not "Employee" but a handle to point to an instance of "Employee" object somewhere sitting in memory.



We have a method call handleEmployee as below which needs Employee object

public void handleEmployee(Employee emp)
{
     // Do Something with employee
    
}

When we call the above method as below
  

      Employee myEmp = new Employee();
      handleEmployee(myEmp);

What essentially happens here is that, we are passing a copy of the handle (myEmp) which was used to access Employee object to the calling method.


Why java pass-by-value ?

Because, we as passing a copy of a reference variable - myEmp, to handleEmployee method ( as emp).

This gives the method handle to get to Employee object but it cannot change myEmp reference itself.

public void handleEmployee(Employee emp)
{
     // Do Something with employee
     emp = null;
}

When we make emp = null, then it just nullifies the copy so that it will no longer refer Employee object. But the original myEmp is still unaffected.

So, as a conclusion, Java is always "pass by value" whether we are passing primitives ( int, char, long, etc) or an object.


No comments: