// Miya Natsuhara // 08-05-2019 // CSE142 // TA: Grace Hopper // An example of value vs. reference semantics. import java.util.*; public class ValueReferenceSemantics { public static void main(String[] args) { int x = 5; int y = 7; swap(x, y); // this method call has no effect on the values of x and y because ints // are primitive types, and so use value semantics. System.out.println("x is " + x + ", y is " + y); int[] arr1 = {12, 3, 39, 23, 10, 0}; int[] arr2 = arr1; arr2[0] = 100; System.out.println("arr1 is " + Arrays.toString(arr1)); modify(arr2); // because of reference semantics, the change made in the modify method // call are reflected when the array is printed out below. System.out.println("arr1 is " + Arrays.toString(arr1)); } // This method swaps the values of a and b locally, but no changes are reflected at the // call site because of reference semantics. // int a: one of the values to be swapped // int b: one of the values to be swapped public static void swap(int a, int b) { int temp = a; // we need this temp variable so we "remember" the old value of a // before the value is squashed by putting b's value in a. a = b; b = temp; System.out.println("a is " + a + ", b is " + b); } // This method takes the given list and puts 99 at index 1 and 666 at index 2. // Because of reference semantics, these changes are reflected at the call site. // int[] list: the list to be modified public static void modify(int[] list) { list[1] = 99; list[2] = 666; } }