// Helene Martin, CSE 142 // Demonstrates the difference between value semantics (primitive types) and // reference semantics (object types). // In Java, primitive types use value semantics so assignment results // in copying a value. Object types use reference semantics so assignment // results in copying a REFERENCE (memory location) to an object. import java.util.*; public class ValueReferenceSemantics { public static void main(String[] args) { int a = 7; int b = 35; // this call has no effect because integers are // copied when passed into a method (value semantics) swap(a, b); System.out.println(a + " " + b); // there is only one array but values1 and values2 are // both references to that array (reference semantics) int[] values1 = {56, 23, 21, -11, 67}; int[] values2 = values1; // changing a value from one of the references is visible from // both references values1[0] = 555; System.out.println(Arrays.toString(values1)); System.out.println(Arrays.toString(values2)); swapArr(values1); System.out.println(Arrays.toString(values1)); System.out.println(Arrays.toString(values2)); } // Swaps the first two elements in an array public static void swapArr(int[] arr) { int temp = arr[0]; arr[0] = arr[1]; arr[1] = temp; } // Attempts to swap two integers but because of value semantics, // the change only happens locally to the method public static void swap(int a, int b) { int temp = a; a = b; b = temp; } }