ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Primitive vs Reference Types
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 3.3

Primitive vs Reference Types

Storage, default values, assignment, equality and method invocation compared

12 min readStage 1 · Foundations14 interview questions
Prerequisites
3.1 Primitive Types · 3.2 Reference Types
Covers
Storage · Default values · Assignment · Equality · Method invocation
Related
4.2 Objects · 4.4 Methods (pass-by-value) · 3.5 Wrapper Classes · Book 2 Vol II (object layout)
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

The difference between the two type families can be stated in one sentence: a primitive variable holds a value; a reference variable holds a reference to an object that lives elsewhere. Everything else in this topic — how they are stored, what they default to, what assignment copies, what == compares and what a method receives — follows from that one rule.

A primitive slot holds the value itself; a reference slot holds the route to an object on the heap
Figure 1 — A primitive slot holds the value itself; a reference slot holds the route to an object on the heap
DimensionPrimitiveReference
Variable holdsThe valueA reference to an object, or null
Where the data livesIn the variable's slot (stack frame, object field, array element)The object is on the heap; only the reference is in the slot
Field default0, 0.0, false, '\u0000'null
Assignment copiesThe valueThe reference (aliasing)
== comparesValuesIdentity (same object?)
Passed to a method asA copy of the valueA copy of the reference
Can be nullNoYes
Usable as generic type argumentNo (needs boxing)Yes

2Why It Exists

The split is a performance decision made in 1995 and still visible today. Numbers and flags are used constantly and must be fast and compact, so they are stored directly. Objects are variable in size and shared, so they are stored once and referred to. The cost of the split is conceptual: two sets of rules for assignment, equality and passing, and a bridge (boxing) where the two meet.

3Core Concepts

Storage

A local variable lives in a slot of the current method's stack frame; a field lives inside its object; an array element lives inside its array. For a primitive, the slot contains the number. For a reference, the slot contains a reference, and the object it refers to is always on the heap (unless the JIT's escape analysis proves it never escapes and eliminates the allocation — an optimisation, not a language rule).

Consequences: primitives are compact and fast to read; objects add a header (typically 12–16 bytes) and require following a reference; and an object's lifetime is independent of the variable that refers to it.

Default values

Fields and array elements are initialised automatically: numeric primitives to zero, boolean to false, char to '\u0000', and every reference type to null. Local variables of either family have no default and must be assigned (2.3).

Defaults, null and generics for the two families
Figure 2 — Defaults, null and generics for the two families

A default of null is where NullPointerException comes from: a reference field that was never assigned points to no object, and calling a method on it fails. Primitive fields can never be null, which is why a Customer.age field of type int cannot express "unknown" — that is a design choice between int with a sentinel value, Integer (nullable) or OptionalInt.

Assignment

Assignment always copies the contents of the slot. For a primitive, that is the value, so the two variables are independent afterwards. For a reference, that is the reference, so both variables now refer to the same object — they are aliases. Changing the object through one name is visible through the other; reassigning one name does not affect the other.

Primitive assignment copies the value; reference assignment creates an alias
Figure 3 — Primitive assignment copies the value; reference assignment creates an alias

Equality

== compares slot contents. For primitives, it compares values. For references, it compares identity: whether both refer to the very same object. Logical equality — "do these two objects represent the same value?" — is defined by the equals method, which classes such as String, BigDecimal, wrappers and records override.

Two String objects with the same content are equal but not identical
Figure 4 — Two String objects with the same content are equal but not identical

Three refinements matter in practice. equals must be paired with a consistent hashCode for objects used in hash-based collections (Book 1 Volume II). BigDecimal.equals also compares scale, so 2.0 and 2.00 are not equal — use compareTo for numeric comparison. And Objects.equals(a, b) is the null-safe way to compare two references that might be null.

Method invocation

Java passes every argument by value: the method receives a copy of the argument's slot. For a primitive, the method gets a copy of the number and cannot change the caller's variable. For a reference, the method gets a copy of the reference: it can use that copy to modify the object the caller also sees, but reassigning its parameter to a new object has no effect on the caller's variable.

The method's copy of the reference reaches the same object; reassigning it affects only the copy
Figure 5 — The method's copy of the reference reaches the same object; reassigning it affects only the copy

4How It Works Internally

In bytecode the two families use different instructions: iload/istore, ladd, dcmpl and so on for primitives; aload/astore, getfield and invokevirtual for references. Comparing references with == compiles to if_acmpeq, a single pointer comparison. Calling equals is an ordinary virtual method call.

On a 64-bit HotSpot JVM with compressed references (the default for heaps below about 32 GB), a reference occupies 4 bytes and is decoded to a full address when used. An object carries a header — mark word and class pointer — before its fields, so even an object with a single int field occupies about 16 bytes. This is why a million Integer objects cost several times more than a million int values (3.5).

5APIs / Features / Syntax

APIUse
Objects.equals(a, b)Null-safe logical equality
Objects.hash(...)Build a hashCode consistent with equals
Objects.requireNonNull(x, msg)Fail fast on null at API boundaries
a.compareTo(b) == 0Numeric equality for BigDecimal regardless of scale
System.identityHashCode(o)Identity-based hash, ignoring overridden hashCode
Arrays.equals / Arrays.deepEqualsContent comparison for arrays (arrays do not override equals)

6Practical Examples

Example 1 — Aliasing

JAVAAssignment semantics
int a = 5;
int b = a;
b = 9;
System.out.println(a);            // 5 — independent copy

List<String> x = new ArrayList<>(List.of("pen"));
List<String> y = x;               // alias: same list object
y.add("book");
System.out.println(x);            // [pen, book] — change visible through x
y = new ArrayList<>();            // reassign y only
System.out.println(x);            // [pen, book] — x unaffected

Example 2 — Mini program: one cart, every rule in one run

Problem. Section 3 lists five rules: what assignment copies, what a method receives, what it can change, what == compares and what a field defaults to. This program applies all of them to one shopping cart and prints the result after each step.

JAVACartRules.java
import java.util.ArrayList;
import java.util.List;
 
public class CartRules {
    static class Cart {
        final List<String> items = new ArrayList<>();
        int discount;                                   // percent, default 0
        public String toString() { return items + " -" + discount + "%"; }
    }
 
    static void addGift(Cart c) { c.items.add("gift"); }  // mutates the object
    static void reset(Cart c) { c = new Cart(); }          // only the copy
    static void bump(int percent) { percent += 5; }        // only the copy
 
    static Cart withDiscount(Cart c, int percent) {  // returns a new value
        Cart copy = new Cart();
        copy.items.addAll(c.items);
        copy.discount = percent;
        return copy;
    }
 
    public static void main(String[] args) {
        Cart mine = new Cart();
        mine.items.add("pen");
        Cart alias = mine;                              // copies the reference
        alias.items.add("ink");
        System.out.println("1 alias       : " + mine);
 
        addGift(mine);
        reset(mine);
        int pct = 10;
        bump(pct);
        System.out.println("2 after calls : " + mine + ", pct=" + pct);
 
        Cart offer = withDiscount(mine, pct);
        System.out.println("3 returned    : " + offer + ", original " + mine);
        System.out.println("4 == / equals : " + (offer == mine) + " "
                + offer.items.equals(mine.items));
    }
}
OUTPUT
1 alias       : [pen, ink] -0%
2 after calls : [pen, ink, gift] -0%, pct=10
3 returned    : [pen, ink, gift] -10%, original [pen, ink, gift] -0%
4 == / equals : false true

Why it behaves this way. Line 1: alias = mine copies the reference, so adding through alias changes the one cart. Line 2: addGift receives a copy of the reference and uses it to change the shared object, so the gift is visible; reset reassigns only its own copy, so the caller's cart is untouched; and bump changes a copy of the int, so pct stays 10. Line 3: returning a new object is how a method gives the caller a different value. Line 4: the two carts are different objects, so == is false, while their lists are equal by content.

Example 3 — Equality

JAVA== versus equals
String a = new String("order-42");
String b = new String("order-42");
System.out.println(a == b);               // false: two objects
System.out.println(a.equals(b));          // true: same content

int[] p = {1, 2}, q = {1, 2};
System.out.println(p.equals(q));          // false: arrays use identity equals
System.out.println(Arrays.equals(p, q));  // true

BigDecimal two = new BigDecimal("2.0"), twoPoint = new BigDecimal("2.00");
System.out.println(two.equals(twoPoint));        // false: different scale
System.out.println(two.compareTo(twoPoint) == 0); // true: same value

Example 4 — A mutable object used as a HashSet key

Problem. Section 3 notes that equals and hashCode must be consistent. They must also stay stable while an object is inside a hash-based collection. Here a key is changed after it was added.

JAVAMutableKey.java
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
 
public class MutableKey {
    static final class Sku {  // equals and hashCode use a mutable field
        String code;
        Sku(String code) { this.code = code; }
        @Override public boolean equals(Object o) {
            return o instanceof Sku s && Objects.equals(code, s.code);
        }
        @Override public int hashCode() { return Objects.hashCode(code); }
    }
 
    record SkuValue(String code) {}              // immutable: safe as a key
 
    public static void main(String[] args) {
        Set<Sku> skus = new HashSet<>();
        Sku pen = new Sku("PEN-1");
        skus.add(pen);
        pen.code = "PEN-2";                      // changed while inside the set
        System.out.println("contains(pen)   : " + skus.contains(pen));
        boolean found = skus.contains(new Sku("PEN-2"));
        System.out.println("contains(PEN-2) : " + found);
        System.out.println("size, element   : " + skus.size() + ", "
                + skus.iterator().next().code);
        Set<SkuValue> values = new HashSet<>(Set.of(new SkuValue("PEN-1")));
        boolean ok = values.contains(new SkuValue("PEN-1"));
        System.out.println("record key      : " + ok);
    }
}
OUTPUT
contains(pen)   : false
contains(PEN-2) : false
size, element   : 1, PEN-2
record key      : true

Why it behaves this way. HashSet puts each element in a bucket chosen by its hash code at the moment it is added (Figure 6). Changing code changes the hash code, but the entry stays in its old bucket, so every lookup, even with the very same object, searches the wrong bucket and returns false, while iteration still finds the element. The set now holds an object it cannot find or remove: a memory leak and a correctness bug at once. A record with final components cannot change, so it is a safe key.

A key changed after insertion stays in its old bucket
Figure 6 — A key changed after insertion stays in its old bucket

Example 5 — What a method can and cannot change

JAVAPass-by-value of a reference
static void applyDiscount(Cart cart, int percent) {
    cart.setTotal(cart.total() * (100 - percent) / 100);  // visible to caller
    percent = 0;                                           // local copy only
    cart = new Cart();                                     // local copy only
}

Cart cart = new Cart(100);
int pct = 10;
applyDiscount(cart, pct);
System.out.println(cart.total() + " " + pct);   // 90 10

Example 6 — Defensive copies at boundaries

JAVABreaking unwanted aliasing
public final class Order {
    private final List<Line> lines;

    public Order(List<Line> lines) {
        // caller's later changes cannot leak in
        this.lines = List.copyOf(lines);
    }

    public List<Line> lines() {
        return lines;                        // already unmodifiable
    }
}

Example 7 — Measuring the footprint: int[] versus Integer[]

Problem. Q8 claims that a million Integer objects cost several times as much as a million int values. This program measures it with the JVM's per-thread allocation counter, a HotSpot extension of ThreadMXBean.

JAVAFootprint.java
import java.lang.management.ManagementFactory;
import java.util.Locale;
 
public class Footprint {
    static final com.sun.management.ThreadMXBean MX =
        (com.sun.management.ThreadMXBean) ManagementFactory.getThreadMXBean();
    static Object keep;  // keeps the arrays reachable
 
    static long allocated(Runnable r) {
        long before = MX.getCurrentThreadAllocatedBytes();
        r.run();
        return MX.getCurrentThreadAllocatedBytes() - before;
    }
 
    public static void main(String[] args) {
        int n = 1_000_000;
        allocated(() -> keep = new Integer[10]);     // warm up the measurement
        long prim = allocated(() -> {
            int[] a = new int[n];
            for (int i = 0; i < n; i++) a[i] = i;
            keep = a;
        });
        long boxed = allocated(() -> {
            Integer[] a = new Integer[n];
            for (int i = 0; i < n; i++) a[i] = i;  // boxing: valueOf
            keep = a;
        });
        System.out.printf(Locale.ROOT, "int[1000000]     : %,d bytes%n", prim);
        System.out.printf(Locale.ROOT, "Integer[1000000] : %,d bytes%n", boxed);
        double ratio = (double) boxed / prim;
        System.out.printf(Locale.ROOT, "ratio            : %.1f%n", ratio);
    }
}

Output on JDK 21 with the default compressed references (the exact byte counts vary slightly between JVMs):

OUTPUT
int[1000000]     : 4,000,232 bytes
Integer[1000000] : 19,997,968 bytes
ratio            : 5.0

Why it behaves this way. The int[] is one object: a 16-byte header plus 4 bytes per element (the few hundred extra bytes are the lambda and the measurement itself). The Integer[] is an array of 4-byte references plus 999,872 separate Integer objects of 16 bytes each; the values 0 to 127 come from the Integer cache and cost nothing (3.5). 4,000,016 + 999,872 × 16 = 19,997,968 bytes, five times the primitive array, and the garbage collector must trace a million extra objects.

7Common Problems & Mistakes

MistakeWhat goes wrongFix
Comparing strings or wrappers with ==Works in tests (cached or interned values), fails in productionUse equals / Objects.equals
Assuming a method cannot change an argument objectCaller's object mutated unexpectedlyDocument mutation; prefer immutable parameters
Assuming a method can reassign the caller's variableChange silently lostReturn the new value instead
Storing a caller's mutable list directlyExternal code modifies internal stateDefensive copy (List.copyOf)
Using array.equalsIdentity comparisonArrays.equals / deepEquals
BigDecimal.equals for amounts2.0 ≠ 2.00compareTo, or normalise scale
Mutable objects as keys in HashMap or HashSetChanging a key strands its entry: lookups fail and the entry cannot be removedImmutable keys, such as records (Example 4)
A setter that stores the caller's array or collectionThe caller keeps an alias and changes the object's state laterCopy on the way in and, if needed, on the way out
== to compare entities loaded from a databaseTwo loads of the same row may give two objectsCompare by identifier; define equals on the ID for entities

8Performance & Production Considerations

  • Primitive arrays are dense and cache-friendly; arrays of objects are arrays of references to objects scattered across the heap, which costs memory and CPU cache misses.
  • Every object allocation adds GC work. In hot paths, avoid creating short-lived wrapper objects needlessly (3.5), though the JIT removes many such allocations through escape analysis.
  • Identity comparison (==) is a single instruction; equals may be expensive for large objects. Hash-based collections call both hashCode and equals.

9Architecture & Design Considerations

The aliasing rule is at the heart of several architecture-level concerns:

  • Encapsulation — any object handed out by reference can be modified by the receiver. Immutable types (records, List.copyOf, value objects) eliminate a whole class of bugs across module boundaries.
  • Concurrency — shared references to mutable objects are the root of data races. Immutable objects can be shared freely between threads.
  • Caching — returning cached mutable objects lets one caller corrupt data for all others. Cache immutable values, or copy on read.
  • Domain modelling — entities have identity (compare by ID); value objects have no identity (compare by all fields, typically records).

10Interview Questions & Answers

Q1L1 · BasicConcept

What is the main difference between a primitive and a reference type?

A primitive variable holds its value directly. A reference variable holds a reference to an object on the heap, or null. Assignment, == and method calls all work on that slot content, which is why the two families behave differently.

Q2L1 · BasicConcept

What are the default values of fields of each kind?

Numeric primitives default to 0 or 0.0, boolean to false, char to '\u0000', and all reference types to null. Local variables of both kinds have no default.

Q3L2 · IntermediateConcept

What is the difference between == and equals?

== compares slot contents: values for primitives, identity for references. equals is a method that defines logical equality; Object.equals uses identity, and value-like classes such as String, wrappers, BigDecimal and records override it to compare content.

Q4L2 · IntermediateConcept

What happens when you assign one reference variable to another?

The reference is copied, so both variables refer to the same object. Mutating the object through either variable is visible through both; reassigning one variable does not affect the other.

Q5L3 · Senior EngineerTricky

Is Java pass-by-value or pass-by-reference?

Always pass-by-value. For references, the value passed is a copy of the reference. The method can mutate the object through its copy, but it cannot make the caller's variable refer to a different object — which is exactly what pass-by-reference would allow.

Q6L3 · Senior EngineerTricky

Why can two BigDecimal values that are numerically equal return false from equals?

BigDecimal.equals considers both value and scale, so 2.0 (scale 1) and 2.00 (scale 2) are not equal. Use compareTo(...) == 0 for numeric equality, or normalise the scale, and be careful when BigDecimal is used as a map key.

Q7L3 · Senior EngineerScenario

A cached configuration object was corrupted for all users after one request modified it. What happened and how do you prevent it?

The cache returned a reference to a shared mutable object. One caller changed it through its alias, and every other holder of the reference saw the change. Cache immutable objects, return defensive copies, or expose read-only views.

Q8L3 · Senior EngineerInternals

Why does an array of one million Integer objects use far more memory than int[1000000]?

The int array stores 4 bytes per value in one contiguous object. The Integer array stores a reference per element plus a separate object per value, each with a header and padding — roughly 16 bytes per object plus 4 per reference. Access also needs an extra indirection and scatters data across the heap.

Q9L4 · Technical ArchitectDesign

How do value objects and entities relate to Java's equality model?

Value objects are defined by their attributes and should be immutable with equals and hashCode over all fields — records fit this. Entities have identity over time, so equality is based on a stable identifier rather than all fields, and they are usually mutable. Mixing the two leads to bugs in collections and persistence.

Q10L4 · Technical ArchitectTrade-off

Where does the primitive/reference split cause problems at system scale, and how do you mitigate them?

Memory footprint of boxed collections in large caches, GC pressure from many small objects, NullPointerExceptions from unassigned references, and data races from shared mutable objects. Mitigations: primitive-specialised collections or arrays for large numeric data, immutable value types, explicit null handling at boundaries, and measuring allocation with profilers such as JFR.

Q11L5 · Solution ArchitectDesign

How would you set team-wide guidelines around these semantics for a large codebase?

Codify: compare objects with equals (static-analysis rule flagging == on non-enum references); make DTOs and value objects records; defensive copies at API boundaries; no mutable public static fields; Money as a value type; nullability annotations on public APIs. Back them with code-review checklists and automated checks, because these bugs pass unit tests easily and appear only under production data or load.

Q12L2 · IntermediateCode

What does this program print?

JAVAAliasQuiz.java
import java.util.ArrayList;
import java.util.List;
 
public class AliasQuiz {
    public static void main(String[] args) {
        List<String> a = new ArrayList<>(List.of("x"));
        List<String> b = a;
        List<String> c = new ArrayList<>(a);
        b.add("y");
        c.add("z");
        System.out.println(a + " " + b + " " + c);
        System.out.println((a == b) + " " + (a == c));
        System.out.println(a.equals(List.of("x", "y")));
    }
}

It prints [x, y] [x, y] [x, z], true false, true. b = a copies the reference, so a and b are one list and both show "y". new ArrayList<>(a) copies the elements into a new list, so c changes independently. == is true only for the alias, while equals compares content, and a List.of with the same elements is equal to the ArrayList because List.equals is defined by elements and order, not by class.

Q13L3 · Senior EngineerCode

Does this swap method work? What does the program print?

JAVASwapQuiz.java
public class SwapQuiz {
    static void swap(StringBuilder p, StringBuilder q) {
        StringBuilder tmp = p;
        p = q;
        q = tmp;
        p.append("!");
    }
 
    public static void main(String[] args) {
        StringBuilder a = new StringBuilder("A");
        StringBuilder b = new StringBuilder("B");
        swap(a, b);
        System.out.println(a + " " + b);
    }
}

It prints A B!: the swap has no effect for the caller. p and q are copies of the caller's references, so swapping them changes only the method's local variables. After the swap p refers to the caller's b object, so p.append("!") changes that object, which the caller sees as "B!". This is the shortest proof that Java passes references by value: a method can change an object, never which object the caller's variable refers to.

Q14L3 · Senior EngineerTricky

An object was added to a HashSet and is still in it, yet contains() returns false for that very object. How?

Its hash code changed after it was added, because equals and hashCode depend on a field that was then modified (Example 4). The set looks in the bucket for the new hash, finds nothing and returns false; remove fails for the same reason, while iteration and size() still see the element. Keys of hash-based collections must be effectively immutable, at least in the fields used by equals and hashCode; records and value objects satisfy that by construction.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Primitive slot = value; reference slot = reference (or null).
  • Assignment copies the slot: values are independent, references create aliases.
  • == compares values or identity; equals compares logical content.
  • Java is always pass-by-value; references are copied, objects are shared.
  • Immutability and defensive copies turn aliasing from a risk into a design tool.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.