Reference Variables: Pointers to Objects
What You'll Learn
You'll understand that reference variables don't contain the actual object—they store a memory address pointing to where the object lives on the heap.
The Core Idea
When you create an object using new, Java allocates that object on the heap (as you learned in the previous lesson). But what exactly gets stored in your variable?
The variable doesn't hold the object itself—it holds a reference (memory address) to that object.
Think of it like this: when you order a pizza for delivery, you don't carry the entire pizzeria around in your pocket. Instead, you have the pizzeria's address written on a piece of paper. That address tells you where to find the pizza. Similarly, a reference variable holds the "address" where the actual object data lives in memory.
int[] numbers = new int[5];
Here, numbers doesn't contain the array itself. It contains a reference (pointer) to the location in heap memory where the five integers actually exist.
This is fundamentally different from primitives:
int x = 42; // x directly contains the value 42
int[] arr = new int[3]; // arr contains a reference to the array
The variable x holds the actual number 42. The variable arr holds an address pointing to where the array lives.
You can't see or print these memory addresses directly in normal Java code—the JVM manages them behind the scenes—but understanding this concept is crucial for predicting how your code behaves, especially when you assign variables to each other or pass them to methods.
Key Takeaway: Reference variables are like addresses on an envelope—they point to where the real object lives in memory, rather than containing the object's data directly.