Call By Reference and Call By Value

Java always makes a copy of the argument and passes the copy. The called method has a local copy of the data. If the method changes the data it changes the copy, so the original value is not changed. When we pass a primitive like int this make perfect sense. The method gets its own int variable, a copy of the original.

When we pass an object we have to think very precisely. The value that is copied and sent along is a reference or pointer to the object. The method gets its own copy of the pointer, but it doesn’t get its own copy of the object. If the method changes its copy of the pointer to point to a different object the original pointer is not affected. If the method changes some of the attributes of the object, it changes the original object.

In short in java, object references are passed by reference and primitive types are passed by value.

Source: JavaRanch

2 thoughts on “Call By Reference and Call By Value”

  1. nice and wrong.

    If you pass by reference, the callee might change that reference, like in C where you may replace the referenced object:

    foo (A &a)
    a = new A (42);

    That is pass by reference.

    So in Java it is always pass-by-value? It doesn’t make sense. It’s a copy of a reference which is passed – not a reference, not a value.

  2. In java its always pass by value. There’s no concept of pointers in Java. So the example u have given may be apt for C. In java even the reference’s copy is passed so if u tend to change the reference to point to new object then a new object is created on the heap and the reference is made to point to this object but the original reference remains pointing/referring to the object created in the calling function. So we have two objects and two references, one pair in the calling function and one pair in the called function. I hope u have got this. For more info visit:


Leave a Reply