// Tyler Rigsby, CSE 142 // Code that emphasizes value semantics vs reference semantics import java.util.*; public class ValueReferenceSemantics { public static void main(String[] args) { int a = 7; int b = 35; int[] c = {4, 12}; String s = ""; swap(7, 35, c, s); System.out.println("in main: a=" + a + ", b=" + b); System.out.println("c=" + Arrays.toString(c)); int[] values = {3, 2, 1, 4, 5}; reverse(values); System.out.println(Arrays.toString(values)); } // Method to demonstrate value vs reference semantics...see inline comments public static void swap(int a, int b, int[] c, String s) { // swapping primitive variables like this is only reflected inside this method, // because the primitive types are passed-by-value int temp = a; a = b; b = temp; // changing values inside an array are reflected inside of main, because the array // is an object, so it is passed-by-reference. c in this method is thus a reference // to the same array as in main, so main can see our changes to that object temp = c[0]; c[0] = c[1]; c[1] = temp; // however, these operations aren't changing the object, they're changing the reference. // so these changes will be reflected in this method, but not back in main. c = new int[1]; s = "hello"; System.out.println("in method: a=" + a + ", b=" + b); System.out.println("c=" + Arrays.toString(c)); } // takes an array as a parameter and reverses the order of the values in the array public static void reverse(int[] values) { for (int i = 0; i < values.length / 2; i++) { int temp = values[i]; values[i] = values[values.length - (i + 1)]; values[values.length - (i + 1)] = temp; } } }