1.14

Calling Instance Methods

Instance methods are called on objects using dot notation, and calling on null causes a NullPointerException.

1525% of exam
Understand It
Ace It
Context

What this topic is and why it exists

Imagine you've just adopted a puppy named Max.
Max can do things — sit, fetch, roll over — but those tricks only make sense when *Max* performs them.
You wouldn't shout "sit!" into an empty room and expect something to happen.
In Java, objects work the same way.
When you create an object, it carries around abilities called instance methods, and you activate them by calling on that specific object using the dot operator: `max.sit()`.
The dot is like pointing at Max and saying, "Hey, *you* — do this."
Here's where it gets interesting.
What if Max doesn't exist yet?
What if you declared a variable for a puppy but never actually brought one home?
In Java, that variable holds `null` — it points to nothing.
If you try calling `max.sit()` when Max is null, Java panics and throws a `NullPointerException`.
It's the program's way of saying, "You're asking nothing to do something, and I can't handle that."
So remember two things: always call instance methods on a real object using the dot operator, and always make sure that object actually exists before you ask it to do anything.
A null reference is an empty leash — and empty leashes don't fetch.
1 / 9