Incremental Java
The Problem With Swapping Ints

The Problem With Swapping Ints

Let's write a method to swap two int's.
public static void swap( int first, int second )
{
   int temp = first ;
   first = second ;
   second = temp ;
}
Let's say we had the following method call to swap():
public static void main( String [] args )
{
   int x = 3 , y = 5 ;
   swap( x, y ) ;
   System.out.println( "x = " + x + " y = " + y ) ;
}
What prints out? The answer may surprise you.
x = 3 y = 5
It didn't swap! Why not?

Pass by Value

The reason it didn't swap is because primitive variables are passed by value. This is what happens:
  1. Arguments are evaluated to values
  2. Boxes for parameter variables are created
  3. Boxes are initialized to the argument values.
In other words, we make a copy of the argument values to the parameter variables.

In the method swap(), we are swapping copies of the original values, instead of the original values. Since local variables and parameter variables disappear after you exit the method, the swapped values also disappear.

So why did the swap work for an ArrayList?

Handles are Pass by Value

When we pass an object as an argument to a method, a box is also created for the parameter. This box holds a copy of the handle. Thus, the parameter and the argument both have a handle, but to the same balloon (object).

Thus, any modification to the parameter modifies the same balloon as if you had modified it at the argument.

When we passed list, the ArrayList object to the swap() method, we passed a copy of the handle. Thus, the parameter variable held a handle to the same balloon! Any modifications made in the method were really made.

When we exit the method, the parameter box (and its handle) disappear. But the baloon doesn't! The argument still has a handle to the balloon.

How to Solve Swap?

The surprising answer is that you can't write a method to swap. There are other awkwards ways to do it, but Java doesn't allow swapping, written as a method. That's because of the problem with pass-by-value. It copies!

When we learn about arrays, we'll be able to swap primitive variables. It won't be very elegant, but it'll work.

The solution then, to swapping, is either to do it in an ArrayList or not to write a special method. Just swap using the code at the beginning of the lesson, and do it "inline" (i.e., write the code without making a method call).