4.1 Primitives vs. Object Reference Variables

Key Takeaways

  • A primitive variable holds a primitive value. A reference variable holds a reference to an object or null.

  • Assignment copies the value after any applicable assignment conversion. Assigning a reference to another compatible reference variable does not clone the object.

  • Aliasing lets two variables refer to the same object. A mutation through one StringBuilder alias is visible through the other, while an immutable String always retains its original contents.

  • Between compatible references, == tests whether they refer to the same object or are both null. Numeric and boolean operands follow their own equality rules.

  • Reference fields default to null and local primitives cannot hold null; marking a reference variable final prevents reassigning the reference itself, not mutating the referenced object's fields or array elements

Last updated: November 2026

Primitive Values and Reference Values

To trace Java SE 8 code, distinguish primitive types (boolean, byte, short, char, int, long, float, double) from reference types such as class, interface, and array types.

In the JVM’s abstract model, each method invocation has a frame with local-variable slots, and the heap is the storage area for objects and arrays. Real JVMs can optimize physical storage. You can trace the program without knowing the object’s address or the JVM’s representation of a reference.

  • A local int can hold the value 42.
  • A local StringBuilder variable can hold a reference to a builder or null.
  • Each instance of a class has its own instance fields. A primitive field such as int age holds a value, while a reference field can link to another object.

What Assignment (=) Actually Copies

Assignment first applies any allowed conversion. For example, long wide = intValue; widens an int, and Integer boxed = intValue; boxes it. When both variables have the same type, follow their values:

  • Assigning one primitive variable to another copies the numeric or boolean value. Modifying the copy never alters the original variable.
  • Assigning one reference variable to another copies the reference handle, not the heap object. Both variables now point to the exact same object in heap memory—a relationship called aliasing.
public class ReferenceVsPrimitive {
    public static void main(String[] args) {
        int x = 10;
        int y = x;          // copies literal value 10
        y = 25;             // x stays 10

        StringBuilder sb1 = new StringBuilder("Java");
        StringBuilder sb2 = sb1; // copies reference handle; sb1 and sb2 alias the same object
        sb2.append(" 8");

        System.out.println(x + " | " + sb1);
    }
}

Running ReferenceVsPrimitive prints 10 | Java 8. Because sb1 and sb2 hold copies of the same reference handle, calling sb2.append(" 8") mutates the single StringBuilder instance on the heap, so reading sb1 observes "Java 8".

Aliasing: Mutable Objects vs. Immutable String

Aliasing confuses many candidates when String enters the picture. A String object is immutable: none of its methods alter the character sequence inside an existing String instance. Methods such as concat, toUpperCase, and replace return a result. Some return the original instance when no change is required, such as concat("").

public class StringAliasingDemo {
    public static void main(String[] args) {
        String s1 = new String("OCA");
        String s2 = s1;          // s1 and s2 alias the same String instance

        s1.concat("8");          // returns a new String "OCA8", which is discarded
        System.out.println(s2);  // prints: OCA

        s1 = s1.concat("8");     // s1 is reassigned to the new String "OCA8"
        System.out.println(s1 + " vs " + s2); // prints: OCA8 vs OCA
    }
}

Notice the contrast:

  1. Calling sb2.append(" 8") on a mutable StringBuilder changes the shared heap object in place, affecting every alias.
  2. Calling s1 = s1.concat("8") on an immutable String moves s1 to a different String object while s2 continues pointing to "OCA".

Comparing Values vs. Identities with ==

Apply the equality rule for the operand types:

  • Between two primitives: == compares their values (applying binary numeric promotion when types differ, such as int compared with char or double).
  • Between two references: == tests reference identity—whether both variables refer to the same object or are both null. It does not compare field contents inside two distinct objects.
int a = 65;
char ch = 'A';
System.out.println(a == ch); // true: both represent numeric value 65

StringBuilder b1 = new StringBuilder("hi");
StringBuilder b2 = new StringBuilder("hi");
StringBuilder b3 = b1;

System.out.println(b1 == b2); // false: two separate heap objects
System.out.println(b1 == b3); // true: both point to the same heap object

String n1 = null;
String n2 = null;
System.out.println(n1 == n2); // true: both references are null

Comparing a primitive directly to an unrelated object reference (such as int x = 5; String s = "5"; boolean same = (x == s);) fails to compile with incomparable types: int and String. By contrast, comparing an Integer wrapper to an int triggers unboxing of the Integer to int and compares their numeric values.

Reference null vs. Primitive Non-Nullability

Only reference variables can hold null. Attempting to assign null to any primitive (int count = null; or boolean flag = null;) triggers a compile-time error (incompatible types: <null> cannot be converted to int).

Remember also how field defaults interact with local variable rules:

  • Instance and static reference fields automatically default to null if not explicitly initialized.
  • Local reference variables have no default value. Writing String name; inside a method and passing name to System.out.println(name) before assigning it (even assigning null explicitly) causes a definite-assignment compile error.

final Object Reference Variables

A common Java SE 8 exam trap equates a final reference variable with an immutable object. Marking a reference variable final locks the reference slot so it cannot be reassigned after initialization—it does not freeze the heap object's internal state.

public class FinalReferenceTrap {
    public static void main(String[] args) {
        final StringBuilder sb = new StringBuilder("SE");
        sb.append(" 8");                     // VALID: mutates the heap object
        // sb = new StringBuilder("SE 11");  // COMPILE ERROR: cannot assign a value to final variable sb

        final int[] scores = {10, 20};
        scores[0] = 99;                      // VALID: mutates an element inside the heap array
        // scores = new int[]{1, 2};         // COMPILE ERROR: cannot reassign final reference scores

        System.out.println(sb + " -> " + scores[0]); // prints: SE 8 -> 99
    }
}

Side-by-Side Comparison: Primitives vs. Object References

FeaturePrimitive VariableObject Reference Variable
Value held by the variablePrimitive value such as 42Object reference or null
What = copiesThe primitive value itselfThe reference handle (creates an alias)
What == testsNumeric or boolean equalityObject identity or two null references when both operands are references
Can hold null?No (compile-time error)Yes
Default value as a field0, 0.0, '\u0000', or falsenull
Effect of final modifierVariable value cannot changeReference cannot be reassigned; mutable object fields/elements can still change
Test Your Knowledge

What is the output of compiling and running the following Java SE 8 code snippet?

public class AliasCheck {
    public static void main(String[] args) {
        int num = 5;
        int copy = num;
        copy += 3;
        StringBuilder sb1 = new StringBuilder("A");
        final StringBuilder sb2 = sb1;
        sb2.append("B");
        System.out.println(num + "-" + sb1 + "-" + sb2);
    }
}
A

8-AB-AB

B

5-AB-AB

C

5-A-AB

D

Compilation fails because final variable sb2 cannot be modified via append

Test Your Knowledge

Which statement about null and == in Java SE 8 is accurate?

A

Assigning null to an uninitialized local char variable sets it to '\u0000'

B

Comparing two distinct StringBuilder objects that hold identical text with == returns true

C

An uninitialized local String variable inside a method automatically defaults to null when printed

D

Comparing two String variables that both hold null with == evaluates to true

Test Your Knowledge

Consider the following code inside a main method:

String a = new String("Duke");
String b = a;
a.toLowerCase();
a = a + "!";
System.out.println(a + " " + b);

What does this code print?

A

Duke! Duke

B

duke! duke

C

duke! Duke

D

Duke! Duke!

Sections you finish are checked off in the contents.