Reference Types

Primitive vs Reference

PrimitiveReference
Examplesint, double, booleanString, arrays, Scanner, your classes
Storesthe value itselfa reference to an object on the heap
Can be null?noyes
Has methods?noyes (name.length())
Name stylelowercasestarts with a capital letter
Default value (fields)0 / falsenull

Copying Values vs Copying References

Example

Assigning a primitive copies the value. Assigning a reference copies the arrow, so both variables point to the same object.

public class Main {
    public static void main(String[] args) {
        int a = 10;
        int b = a;     // copy of the value
        b = 20;
        System.out.println("a = " + a + ", b = " + b);

        int[] marks1 = {70, 80, 90};
        int[] marks2 = marks1;   // copy of the reference (same array!)
        marks2[0] = 100;
        System.out.println("marks1[0] = " + marks1[0]);

        String s = null;  // references can be null
        System.out.println("s is " + s);
    }
}

Output

a = 10, b = 20
marks1[0] = 100
s is null

Memory Picture

Stack (method variables)          Heap (objects)
 +-----------------+
 | a = 10          |
 | b = 20          |
 | marks1  ------------+-------->  [100, 80, 90]
 | marks2  ------------+
 +-----------------+

Tip: Calling a method on a null reference throws NullPointerException, the most common runtime error in Java.