Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Pass-by-value Semantics in Java Applications

By Peter Haggar
2003-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


#include
#include

void swap(int *a, int *b);

int main (int argc, char** argv)
{
int val1, val2;
val1 = 10;
val2 = 50;
swap(&val1, &val2);
return 0;
}

void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}

A swap function using references, which are passed by reference, looks like this:

Listing 6: Swap function using references


#include
#include

void swap(int &a, int &b);

int main (int argc, char** argv)
{
int val1, val2;
val1 = 10;
val2 = 50;
swap(val1, val2);
return 0;
}

void swap(int &a, int &b)
{
int temp = b;
b = a;
a = temp;
}

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++


class Swap
{
public static void main(String args[])
{
Integer a, b;

a = new Integer(10);
b = new Integer(50);

System.out.println("before swap...");
System.out.println("a is " + a);
System.out.println("b is " + b);
swap(a, b);
System.out.println("after swap...");
System.out.println("a is " + a);
System.out.println("b is " + b);
}

public static void swap(Integer a, Integer b)
{
Integer temp = a;
a = b;
b = temp;
}
}

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


before swap...
a is 10
b is 50
after swap...
a is 10
b is 50

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


 | Bookmark
Related Tutorials:
» All about JAXP, Part 1
» Make Database Queries Without the Database
» Load List Values for Improved Efficiency
» 2 Ways To Implement Session Tracking
» A Simple Way to Read an XML File in Java
» Develop Aspect-Oriented Java Applications with Eclipse and AJDT