Pass-by-value Semantics in Java Applications
By Peter Haggar2003-11-24
Parameter passing in C++ and Java applications
Variables in Java applications can be one of two types: reference types or primitive types. Both types are handled the same way when passed as arguments to a method. Both are passed by value; neither is passed by reference. This is an important distinction as the subsequent code examples illustrate.
Before going further, it is important to define the terms pass by value and pass by reference. Pass by value means that when an argument is passed to a function, the function receives a copy of the original value. Therefore, if the function modifies the parameter, only the copy is changed and the original value remains unchanged. Pass by reference means that when an argument is passed to a function, the function receives the memory address of the original value, not a copy of the value. Therefore, if the function modifies the parameter, the original value in the calling code is changed.
Some of the confusion about parameter passing in Java applications originates from the fact that many programmers came to Java programming from C++ programming. C++ contains both non-reference types and reference types and passes them by value and by reference, respectively. The Java programming language has primitive types and object references, and therefore, it is logical to think that Java applications use pass by value for the primitive types and pass by reference for references, much like C++. After all, you might think if you are passing a reference, it must be pass by reference. It is tempting to believe this, and in fact it was my belief for some time, but it is not true.
In both C++ and Java applications, when a parameter to a function is not a reference, you pass a copy of the value (pass by value). The difference is with references. In C++ when a parameter to a function is a reference, you are passing the reference, or the memory address (pass by reference). In Java applications, when an object reference is a parameter to a method, you are passing a copy of the reference (pass by value), not the reference itself. Note that the calling method's object reference and the copy are pointing to the same object. This is an important distinction. A Java application does nothing differently when passing parameters of varying types like C++ does. Java applications pass all parameters by value, thus making copies of all parameters regardless of type.
Tutorial Pages:
» Pass-by-value semantics in Java applications
» The key point
» Parameter passing in C++ and Java applications
» Examples
» Writing a swap method
» Resources
First published by IBM DeveloperWorks
