Course contentsShow
← Java
Lesson 279 of 2,8707. Reference Types and Object FundamentalsFree lesson

Assignment Semantics: Primitives vs References

Understand how assignment copies values for primitives but copies references for objects.

Assignment Semantics: Primitives vs References

What you'll learn: How assignment (=) behaves differently for primitives versus reference types.


The Core Difference

When you use the assignment operator in Java, it always copies a value from right to left. However, what gets copied depends on the variable's type:

  • For primitives: The actual data value is copied.
  • For reference types: The memory address (reference) is copied, not the object itself.

Primitives: Independent Copies

int a = 5;
int b = a;  // Copies the value 5
b = 10;     // Only b changes

System.out.println(a);  // Still 5
System.out.println(b);  // Now 10

Variables a and b each have their own copy of the integer value. Changing one doesn't affect the other.

References: Shared Objects

int[] arrayA = new int[]{1, 2, 3};
int[] arrayB = arrayA;  // Copies the reference, not the array
arrayB[0] = 99;         // Modifies the shared object

System.out.println(arrayA[0]);  // 99 (!)
System.out.println(arrayB[0]);  // 99

Both arrayA and arrayB now point to the same array object on the heap. Modifying through one reference affects what you see through the other, because there's only one actual array.

Analogy

Think of primitives like photocopies: each variable gets its own independent copy. References are like street addresses: copying the address doesn't duplicate the house—two people can share the same address and see the same changes inside.

Key Takeaway: Assignment copies values for primitives (creating independence) but copies references for objects (creating shared access to the same object).