/* Java uses pass-by-value * but Object types are all references, so this is similar to pointers in C * We use the swap function to demonstrate that a swap function in Java requires * mutable objects */ public class Swap { // This will swap the values of local variables a and b, but // will have no effect on variables in the calling function public static void swap (int a, int b) { int t = a; a = b; b = t; } // This will swap the references in local variables a and b, // but will have no effect on variables in the calling function public static void swap (Integer a, Integer b) { Integer t = a; a = b; b = t; } // Since this version changes the values in the Objects themselves, // and since the calling code has references to those objects, // this swap will work. public static void swap( Item a, Item b) { int t = a.val; a.val = b.val; b.val = t; } // If change the member of an object referred by the reference // the changes are reflected back, as even it's a copy of // the object's reference, it refers to the same object public static void resetVal (Item item) { item.val = 0; } public static void main (String[] args) { int a = 5; int b = 10; System.out.println("Before swapping a = " + a + " b = " + b); swap(a, b); System.out.println("After swapping a = " + a + " b = " + b); Integer i = 5; Integer j = 10; System.out.println("Before swapping i = " + i + " j = " + j); swap(i, j); System.out.println("After swapping i = " + i + " j = " + j); Item t = new Item(5); System.out.println("Before resetting t.val = " + t.val); resetVal(t); System.out.println("After resetting t.val = " + t.val); Item blah = new Item(5); Item coo = new Item(10); System.out.println("Before swapping blah = " + blah.val + " coo = " + coo.val); swap(blah, coo); System.out.println("After swapping blah = " + blah.val + " coo = " + coo.val); } } class Item { int val; public Item (int v) { val = v; } }