JavaRanch Home    
 
This page:         last edited 15 October 2010         What's Changed?         Edit

Call By Reference Vs 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 value and primitive types are passed by value.

(posted by Stan James in this thread)

Other Resources:


JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton