Java Pass by Reference or Pass by Value

This is very important question “java is pass by value or pass by reference?”. Well, Java is pass by value and not pass by reference. If it had been pass by reference, we should have been able to C like swapping of objects, but we can’t do that in java.

When if you pass an instance(object) to a method, its memory address are copied bit by bit to new reference variable, thus both pointing to same instance. But if you change the reference inside method, original reference will not get change. If it was pass by reference, then it would have got changed also.

To prove it, lets see how memory allocations happen in run time. It should solve the slightest doubts, if any. I am using following program for demonstration of the concept.

public class TestPassByValue{

    private String name;

    public TestPassByValue (String s){
        this.name= s;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {

        this.name= name;

    }
}

public class CheckPassByValue{
     public static void main(String[] args){

          TestPassByValue pv = new TestPassByValue("v");

          changeReference(pv); // It won't change the reference!

          modifyReference(pv); // It will change the object that the reference variable "pv" refers to!
     }

     public static void changeReference(TestPassByValue v) {

          TestPassByValue v1= new TestPassByValue("v2");
          v= v1;

     }

     public static void modifyReference(TestPassByValue v3) {

          v3.setAttribute("v4");

     }
}

 

The Java Spec says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java. These terms are associated with method calling and passing variables as method parameters. Well, primitive types are always pass by value without any confusion. But, the concept should be understood in context of method parameter of complex types.

In java, when we pass a reference of complex types as any method parameters, always the memory address is copied to new reference variable bit by bit. See in below picture:

pass-by-value

In above example, address bits of first instance are copied to another reference variable, thus resulting both references to point a single memory location where actual object is stored. Remember, making another reference to null will not make first reference also null. But, changing state from either reference variable have impact seen in other reference also.

Related Articles

post a comment