Pass-by-value Semantics in Java Applications
By Peter Haggar2003-11-24
Writing a swap method
Given what we know about how parameters are passed, writing a swap function in C++ can be accomplished in different ways. A swap function using pointers, which are passed by value, looks like this:Listing 5: Swap function using pointers
|
A swap function using references, which are passed by reference, looks like this:
Listing 6: Swap function using references |
Both C++ code examples swap the values as expected. If Java applications used pass by reference, the following swap method would work like the C++ examples:
Listing 7: Java swap function if pass by reference worked like in C++ |
Because the Java application passes all parameters by value, this code does not work and produces the following output:
Listing 8: Output from Listing 7 |
So how do you write a method in a Java application to swap the values of two primitive types or two object references? Because a Java application passes all parameters by value, you cannot. To swap the values, you must do so inline, outside of a method call.
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
