AP® Computer Science A · Unit 1 · Topic 1.12
Reference Variables, null, and NullPointerException
A reference variable stores the address of an object, not the object itself. When it holds null, it points at nothing, so calling a method through it throws a NullPointerException.
Objects can be large and variable in size, so Java doesn't stuff them directly into a variable. Instead the object lives on the heap, a big pool of memory for object storage, and the variable holds a reference: the address of where that object sits. When you write String s = "cat"; the three characters live in a String object somewhere on the heap, and s just holds directions to get there. Copying s to another variable copies the address, not the characters.
Before a reference is pointed at any object, it can hold the special value null, which means 'points at nothing.' Declaring String s; and never assigning it, or explicitly writing String s = null;, leaves s with no address to follow. That's fine as long as you don't ask s to do anything that requires an actual object. The trouble starts when you call a method: s.length() means 'go to the object s points at and run its length method.' If s is null there is no object to go to, and Java throws a NullPointerException, a runtime crash reporting that you tried to use a reference that wasn't pointing anywhere.
This sits right after you've learned that variables of object type hold references rather than values, and right before you start calling methods on objects regularly. Every method call through a reference is secretly a two-step trip: follow the address, then run the method on what's there. Keeping that picture in mind is what makes NullPointerException predictable instead of mysterious, since it only ever happens at the dot, when a null reference is asked to do something.
Key terms
- reference
- The address of an object's location in memory, stored in a variable instead of the object itself.
- heap
- The region of memory where all objects are actually stored during a program's execution.
- null
- A special value meaning a reference points at no object at all.
- NullPointerException
- A runtime error thrown when code tries to call a method or access a field through a null reference.
Watch it explained
- How it worksHow does a reference variable point at an object sitting somewhere else in memory?
- How it worksWalk me through what null means and what a reference holds before anything is assigned.
- Worked exampleTrace String s = null; System.out.println(s.length()); and find exactly where it blows up.
- Common mistakeWhy isn't a null reference the same thing as an empty string or a zero?
Check yourself
End of topic.