Friday, July 23, 2010

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;

public static void changeAttribute(A a, A b) {
   a = b;

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


  1. Very nice explanation

  2. Thanks so much - very nice! Another good one:

    Is Java pass by reference?