Java pass by reference or pass by value?

Does Java pass by reference or pass by value?

In Java everything is passed by value. Sometime this is confusing but the point to understand is that in Java, when we pass an parameter to the method, a copy of the parameter is made.

If the argument is the primitive type, then a copy of the value of the primitive is passed. If the argument being passed is an object reference, then a copy of the value of the reference is passed. i.e., the object reference is passed by value.

Consider the example below,

public static void main(String[] args) {
   A a = new A();
   A b = new A();
   a.attribute = 5;
   b.attribute = 7;
   System.out.println(a.attribute);
   System.out.println(b.attribute);
   changeAttribute(a,b);
   System.out.println(a.attribute);
   System.out.println(b.attribute);
}

public static void changeAttribute(A a, A b) {
   a = b;
   System.out.println(a.attribute);
}   

Since Java is pass by value, the caller still does not see the change, even after calling the method.

In short, Java is pass by value for all data types. Non-primitive type variables are references to objects. They are not the objects themselves. Because variables are not the objects themselves, the objects never passed to a method; only a reference to the object is passed.

More Readings

2 comments:

  1. Very nice explanation

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete