All basic types are passed by value. Arrays and Objects are passed by reference. See example below.
The first swap didn't work because int is passed by value.
The second swap works because arrays are passed by reference.
The third won't work because though you pass the Integer arrays by reference, the actual object is not changed inside and only the temporary references are changed. To change the actual object, you will have to use set members. I couldn't show that here because Integer doesn't have something like setValue(). Assuming there's a setValue() method for Integer, The code would look like
int k = i.getInteger();
i.setValue( j.getInteger() );
j.setValue( k );
Swap.java
---------
public class Swap {
public void doSwap( int i, int j )
{
int k=i;
i=j;
j=k;
return;
}
public void doSwap( Integer i, Integer j )
{
Integer k = i;
i = j;
j = k;
return;
}
public void doSwap( int [] i, int [] j )
{
int k = i[0];
i[0] = j[0];
j[0] = k;
return;
}
public static void main(
String [] args)
{
int a=10, b=20;
Swap swap = new Swap();
swap.doSwap( a, b );
System.out.println(" a, b = " + a + ", " +b);
int [] a1 = { 10 };
int [] b1 = { 20 };
swap.doSwap( a1, b1 );
System.out.println(" a1, b1 = " + a1[0] + ", " +b1[0]);
Integer x = new Integer(10);
Integer y = new Integer(20);
swap.doSwap( x, y );
System.out.println(" x, y = " + x + ", " +y);
}
}
[This message has been edited by Sri Bala (edited March 07, 2001).]