skip to content

What is the difference between primitive and reference types in Java: what a variable holds, how null, == and assignment behave, and where values live?

level: juniorimportance: must knowfreq 78%

answer

  1. the value, or a way to reach it
  2. null exists on one side only
  3. == compares what the variable holds
  4. assignment copies, but copies what?
  5. location follows the kind of variable

basics

~20 s

A primitive variable holds the value itself and can never be null; a reference variable holds a reference to a heap object, or null. Assignment copies that value or reference, and == compares values or object identity.

solid answer

~40 s

A primitive variable, such as an `int`, stores the value itself, while a reference variable stores a reference to an object or array, or `null`. `null` applies only to reference types, so `int x = null;` does not compile, and calling an instance method through a null reference throws `NullPointerException`. `==` follows what the variable holds: primitives compare by value and references by object identity, which is why contents need `equals`. Assignment copies the same thing: a copied `int` is independent, but a copied reference means two variables share one object. On location, objects and arrays are on the heap and local variables are in a stack frame. A field's value sits inside its object, even when the field is an `int`.

code

java · 20 lines
java
import java.util.Arrays;

public class PrimitiveVsReference {
    public static void main(String[] args) {
        int a = 1;
        int b = a;                         // copies the value
        b = 2;
        System.out.println(a);             // 1

        int[] x = {1};
        int[] y = x;                       // copies the reference: one array, two variables
        y[0] = 2;
        System.out.println(x[0]);          // 2
        System.out.println(x == y);        // true: same array

        y = new int[] {2};                 // y now refers to a second array; x is untouched
        System.out.println(x == y);        // false: different arrays, equal contents
        System.out.println(Arrays.equals(x, y)); // true: compares the elements
    }
}

go deeper

for a junior

Recall that a primitive variable holds its value and a reference variable holds a reference or null. Give the array example: copying the reference shares one array, and == checks for the same object.

for a middle

Explain the mechanics: assignment and argument passing copy the variable's contents, == compares those contents, and storage follows the kind of variable, so an int field sits inside its heap object while a local sits in a frame.

for a senior

Use the model to diagnose real bugs: aliasing through shared references, surprise NullPointerExceptions and data races, since locals are thread-private while objects may be shared. Do not infer allocation from source, because the JIT can remove objects that do not escape.

for a principal

The tradeoff is layout against modelling: primitive arrays pack data tightly, while object graphs add references and headers. Weigh that cost against clarity in data-heavy code, and measure before setting a team convention either way.

## Two kinds of type Every Java variable and expression has a type known at compile time, and the language divides those types into two kinds. A **variable** is a storage location with a type, such as a local, a parameter, a field or an array element. - **Primitive types** are the eight predefined types named by keywords: `boolean`, `byte`, `short`, `int`, `long`, `char`, `float` and `double`. - **Reference types** are class types, interface types, type variables and array types. `String`, `Integer`, `int[]` and `List<String>` are all reference types. An **object** is a class instance or an array, and a **reference** is the value that points to one. The Java Language Specification (JLS) describes references as pointers to objects. ## What a variable holds A primitive variable always holds a value of its exact primitive type. There is no object behind it and no member to reach, so `count.toString()` on an `int` fails to compile with `int cannot be dereferenced`. A reference variable holds either the **null reference**, which refers to no object, or a reference to an object or array. The object is separate from the variable, and any number of variables can hold references to the same object. ## null, == and assignment | Operation | Primitive variable | Reference variable | |---|---|---| | `null` | `int x = null;` and `x == null` do not compile | A legal value meaning no object | | Instance method call or instance field access | Not available | `NullPointerException` if the reference is null | | `==` | Compares values, promoting numeric operands first | True if both refer to the same object or array, or both are null | | Assignment | Copies the value | Copies the reference, never the object | | Passing an argument | Parameter starts with a copy of the value | Parameter starts with a copy of the reference | Two refinements keep the `==` row honest: - **Floating-point values.** `==` follows IEEE 754, so `NaN == NaN` is false and `-0.0 == 0.0` is true. These cases are covered with special floating-point values. Promotion to `float` or `double` can also lose precision, so `16777217 == 16777216f` is true. - **Mixed operands.** If one operand is numeric and the other converts to numeric, as in `Integer == int`, the wrapper is unboxed and the comparison is numeric. Two `Integer` operands remain a reference comparison. Equal contents are not enough for reference `==`. Two distinct arrays holding the same numbers compare false, and so do two distinct `String` objects with the same characters. Compare contents with `equals`, or with `Arrays.equals` for arrays. Because assignment copies only the reference, this sequence shows the sharing: 1. `int[] x = {1};` creates an array and stores a reference to it in `x`. 2. `int[] y = x;` copies the reference, so both variables now point to one array. 3. `y[0] = 2;` changes that array, and `x[0]` now reads `2`. 4. `y = new int[] {2};` gives `y` a different array and leaves `x` and its array untouched. Method parameters work the same way. A method that changes an object through its parameter changes what the caller sees, while a method that reassigns the parameter leaves the caller's variable alone. ## Where the value lives Location follows the kind of variable, not the kind of type. The JLS stores all instance fields, static fields and array elements in heap memory, and the Java Virtual Machine Specification (JVMS) puts local variables in each method's frame: | Variable | Where it lives | What is stored there | |---|---|---| | Local variable or parameter | Its method's frame, on the thread's JVM stack | The value or the reference | | Instance field | Inside its object, on the heap | The value or the reference | | Array element | Inside its array, on the heap | The value or the reference | | Static field | In heap memory; HotSpot keeps it in the class's `java.lang.Class` object | The value or the reference | So "primitives on the stack, objects on the heap" is only half true. An `int` field is on the heap inside its object, and a local `String` variable is in a frame while the `String` object is on the heap. Two qualifications apply: - **The model does not promise an allocation.** HotSpot's C2 compiler performs escape analysis and can eliminate the allocation of an object that does not escape (`DoEscapeAnalysis` and `EliminateAllocations`, both on by default). - **The JVM stack is a specification term.** The JVMS holds frames there but allows frames to be heap allocated, so it describes a model and not a machine address range. ## Why the distinction matters - **Aliasing.** A change made through one reference appears through every other reference to that object. A separate copy needs a deliberate step, such as `clone()` on an array. - **Null handling.** A method call on a primitive does not compile, so `NullPointerException` from a member access can only come from a reference. Field defaults differ too, `0` against `null`, which is covered with default values. - **Threads.** Local variables and parameters are never shared between threads. A local reference is private in the same way, but the object it refers to may be reachable from other threads.

  • If assignment copies a reference, does Java pass objects to methods by reference?
    No. Each parameter is a new variable initialized with the argument's value, and for a reference type that value is the reference. Changing the object through the parameter is visible to the caller, because both refer to one object. Reassigning the parameter changes only the parameter, so the caller's variable keeps its reference.
  • Does == on two numeric primitives always mean the values are the same?
    For two integer operands, yes. A mixed comparison promotes first and may lose precision, so `16777217 == 16777216f` is true. Floating-point operands follow IEEE 754: any comparison with `NaN` using `==` is false, even `x == x`, and `-0.0 == 0.0` is true though the two are distinguishable values. So `x != x` is true exactly when `x` is `NaN`.
  • Does HotSpot really allocate every object on the heap?
    Not always. The JVMS says the heap is where memory for class instances and arrays is allocated, but HotSpot's C2 compiler runs escape analysis and can eliminate the allocation of an object that does not escape. `DoEscapeAnalysis` and `EliminateAllocations` are on by default. So reason from the model for behaviour, and do not read allocation counts from the source.

A primitive variable is a slip of paper with a number written on it; a reference variable is a slip with a house address. Copying a number slip gives an independent number. Copying an address slip gives a second way to reach the same house, so repainting the house through one slip shows through the other, and a blank slip is null. Comparing two address slips says whether they name the same house, not whether two houses look alike.

  • Every primitive lives on the stack, including an int field of an object.
  • Assigning one object variable to another copies the object.
  • Using == on two objects compares their contents.
  • An int variable holds null until it is first assigned.
  • A reference variable contains the object itself, fields included.
  • Java passes objects by reference, so reassigning a parameter changes the caller's variable.

context