Primitives vs references in Java
Primitives hold values; reference variables hold a pointer to an object or null.
Cash vs a locker note
A primitive variable holds its value directly, like cash in your hand. A reference variable (any class, interface or array type, like String or int[]) holds the address of an object stored elsewhere, like a note with a locker number.
Your turn
What does this print?
int a = 3;
int b = a;
b = 8;
System.out.println(a);
System.out.println(b);3 88 83 3
Show the answer
int b = a; copies the value 3 into b. Changing b afterwards doesn't touch a. Output: 3 then 8.
Copying a reference shares the object
Arrays are objects. int[] b = a; copies the address, not the array. Now a and b point to the same array, so a change made through one is visible through the other.
int[] a = {5};
int[] b = a; // same array!
b[0] = 9;
// a[0] is now 9 tooYour turn
What does this print?
int[] x = {1, 2};
int[] y = x;
y[1] = 50;
System.out.println(x[1]);250Compile error
Show the answer
50. x and y refer to the very same array object, so y[1] = 50 changes what x[1] sees.
null: the blank note
A reference can be null, meaning it points to no object. Only reference types can be null. An int, double or boolean always contains a value.
String name = null; // ok
int count = null; // errorCalling a method on null
There's no object to ask for its length, so the JVM throws NullPointerException. It compiles fine and blows up at runtime.
String name = null;
System.out.println(name.length());
// NullPointerExceptionIn real projects
NullPointerException is the most famous crash in Java. Tony Hoare, who introduced null references in 1965, later called them his "billion-dollar mistake". Since Java 14, NPE messages name exactly which variable was null.
Key takeaways
- int b = a; copies the number
- int[] b = a; copies the reference: same array
- Only reference variables can be null
- Calling a method on null → NullPointerException
💡 A primitive is cash in your hand; a reference is a note with the address of a locker.
Java references can't be used for pointer arithmetic: you can't add to them or turn them into numbers. That rule removes whole families of memory bugs common in C.
Practice questions
What does this print?
int a = 5;
int b = a;
b = 9;
System.out.println(a);- 9
- 14
- 5
- 0
Check your answer
5. b = a copies the value 5 into b. Changing b afterwards doesn't affect a.
What does this print?
int[] a = {5};
int[] b = a;
b[0] = 9;
System.out.println(a[0]);- 9
- 5
- 0
- Compile error
Check your answer
9. Arrays are objects. b = a copies the reference, so a and b point at the same array, and the change is visible through both.