// Kyle Thayer, CSE 142 // An example of value versus reference semantics. import java.util.*; public class ValueReferenceSemantics { public static void main(String[] args) { // Value semantics: With simple types (like ints), the // swap method wont change the values main has. int x0 = 7; int x1 = 35; System.out.println("before: x0 = " + x0 + ", x1 = " + x1); swap(x0, x1); // Values will not be swapped System.out.println("after: x0 = " + x0 + ", x1 = " + x1); System.out.println(); // Reference semantics: With objects (like int[]), the // swapArray method will change the array that main has. // The array in main will be changed by the swapArray method. int[] x = {7, 35}; System.out.println("before: x[0] = " + x[0] + ", x[1] = " + x[1]); swapArray(x); // Values will be swapped System.out.println("after x[0] = " + x[0] + ", x[1] = " + x[1]); System.out.println(); } // This method swaps the values of the two ints, x0 and x1 that // were passed in. Since ints are passed by value, this will have // no effect on what main sees. public static void swap(int x0, int x1){ int temp = x0; x0 = x1; x1 = temp; } // This method swaps the first two values in the array of ints (x) // that was passed in. Since the int[] is passed by reference, // When main looks at the int[] after this method was called, it will // see that the values were swapped. public static void swapArray(int[] x){ int temp = x[0]; x[0] = x[1]; x[1] = temp; } }