Calling Instance Methods
Why this matters
Imagine you're at a food truck festival in Austin. There's a taco truck, a pizza truck, and a smoothie truck. Each truck is an "object." You wouldn't go to the pizza truck and ask for a taco. You walk up to the specific truck you want—the taco truck—and give it a command: "I'd like one al pastor taco." You've just "called a method" on the "taco truck object."
In programming, we do the same thing. We don't just shout commands into the void; we direct our requests to specific objects that know how to handle them. Today, we'll learn the precise Java syntax for telling objects what to do, how to understand their responses, and how to avoid the common error of talking to a truck that isn't even there.
Concept overview
flowchart TD
A[Start] --> B{Is object reference null?};
B -->|No| C[Call method using dot operator: object.method()];
C --> D[Method executes];
D --> E[Program continues];
B -->|Yes| F(NullPointerException);
F --> G[Program crashes];
Core explanation
Hello there! I'm Saavi, and I'm so glad you're here. Let's dive into one of the most fundamental actions in programming: making things happen.
So far, you know that a class is a blueprint (like the blueprint for a Ford Mustang) and an object is a specific instance created from that blueprint (like your specific red Mustang in the driveway).
Instance methods are the actions that a specific object can perform. The blueprint—the Mustang class—defines that a Mustang can accelerate(), brake(), and turnOnRadio(). But you don't ask the blueprint to accelerate. You ask your specific car to do it.
The Dot Operator: Your Command Button
So how do you tell your specific car object to accelerate? You use the dot operator (.).
Think of it like a TV remote. Your SamsungTV object sits in the living room. Your remote is the tool you use to command it. The dot is like pointing the remote at the TV and pressing a button.
The syntax looks like this:
objectName.methodName();
Let's break it down with a String object, which you've already seen.
// 1. Create a String object
String teamName = "Seattle Seahawks";
// 2. Call the length() method on the teamName object
int len = teamName.length(); // len is now 16
<figure class="lesson-figure"><div class="shr-widget" data-shr-widget="{"code":["String teamName = \"Seattle Seahawks\";","int len = teamName.length();","String loudName = teamName.toUpperCase();"],"type":"for_loop_trace","array":[],"trace_steps":[{"line":1,"vars":{"teamName":"\"Seattle Seahawks\""}},{"line":2,"vars":{"len":16,"teamName":"\"Seattle Seahawks\""}},{"line":3,"vars":{"len":16,"loudName":"\"SEATTLE SEAHAWKS\"","teamName":"\"Seattle Seahawks\""}}]}" aria-label="Animation showing Java code executing. Variables `teamName`, `len`, and `loudName` update as `length()` and `toUpperCase()` methods are called on `teamName`."></div><figcaption class="lesson-figure-caption">Tracing String method calls: `length()` and `toUpperCase()`.</figcaption></figure>
// 3. Call the toUpperCase() method on the teamName object
String loudName = teamName.toUpperCase(); // loudName is now "SEATTLE SEAHAWKS"
In this code:
teamNameis the object. It's our specific thing.- The
.is the dot operator. It connects the object to the command. length()andtoUpperCase()are the instance methods. They are actions theStringclass blueprint says allStringobjects can do.
Notice the parentheses () after the method name. You must include them, even if there's nothing inside. They are what signal to Java that you are calling a method.
"But Where Does the Object Come From?"
This is a great question. You get an object in one of two ways for now:
- You construct it yourself using the
newkeyword (e.g.,Rectangle box = new Rectangle();). - A method gives one back to you (e.g.,
teamName.toUpperCase()gives you a newStringobject).
The key is that you must have a variable that points to an actual object before you can call a method on it.
The Dreaded NullPointerException
What happens if you have a remote but no TV? What if you have a dog leash but no dog at the end of it? If you try to give a command—"turn on," "fetch"—what happens?
Nothing. Or rather, in Java, your program crashes.
In Java, the keyword null means "no object." It's a placeholder for a variable that doesn't point to anything yet. It's the empty leash.
Look at this code:
// Create a String variable, but don't assign it an object.
// It points to nothing.
String studentName = null;
// Now, try to ask it for its length.
int nameLength = studentName.length(); // CRASH!
When the computer tries to run studentName.length(), it follows the studentName variable to find the object. But it finds null. It finds the empty leash. The program immediately stops and throws a NullPointerException.
The error message is your friend. It's Java's way of telling you, "Hey, you told me to call a method on an object, but the variable you gave me was null!"
To summarize:
- You call instance methods on objects, not classes.
- You use the dot operator (
.) to connect the object to the method. objectName.methodName();- Trying to call a method on a
nullreference causes aNullPointerExceptionand crashes your program.
Learning to read your code and trace which variables might be null is a superpower. Let's start developing it.
See it in action
Worked examples
Let's walk through a couple of examples together. The goal here isn't just to get the right answer, but to understand the process of thinking like a programmer.
Example 1: Using the String Class
Problem: You are given a String variable containing a person's full name. Write code to find the number of characters in the name and also create a new string that is the "yell-able" version of the name (all uppercase).
Solution Walkthrough:
-
Set up the initial object. We need a
Stringto work with.String fullName = "Priya Sharma";Here,
fullNameis our object reference. It points to aStringobject in memory that holds the characters "Priya Sharma". -
Call the
length()method. The problem asks for the number of characters. We know from theStringclass documentation (or from memory!) that thelength()method does this.int charCount = fullName.length(); -
Call the
toUpperCase()method. The problem asks for a "yell-able" version. ThetoUpperCase()method is perfect for this.String shoutedName = fullName.toUpperCase(); -
Display the results.
System.out.println("Original: " + fullName); // Prints "Priya Sharma" System.out.println("Character count: " + charCount); // Prints 12 System.out.println("Shouted: " + shoutedName); // Prints "PRIYA SHARMA"
Example 2: The NullPointerException in Action
Problem: Your friend wrote some code to get the first initial from a name, but it keeps crashing. Find the bug.
// Friend's code
String middleName = null; // This person doesn't have a middle name
String initial = middleName.substring(0, 1);
System.out.println("The initial is: " + initial);
Solution Walkthrough:
- 1Trace the variableWe start at the first line:
String middleName = null;. We immediately see thenullkeyword. This should set off alarm bells in our heads. ThemiddleNamevariable is an empty leash—it's not pointing to anyStringobject. - 2Analyze the method callThe next line is
String initial = middleName.substring(0, 1);. The code is attempting to call thesubstring()method. - 3Connect the dots (or the lack thereof)To call
substring(), Java needs an object. It looks at themiddleNamevariable. What does it find?null. - 4Identify the errorThe computer cannot execute a method on
null. It's like asking an empty parking space to start its engine. At this exact point, the program will halt and throw aNullPointerException. TheSystem.out.printlnline will never even be reached.
The Fix: The code needs to handle the case where middleName might be null. A more advanced way uses an if statement (which we'll cover later), but for now, the bug is simply that you cannot call a method on null. The fix is to not write code that does this!
Try it yourself
Time to get your hands on the keyboard. Don't worry about getting it perfect the first time; the goal is to try.
Practice 1: The Rectangle Class
Assume you have a Rectangle class available that you can create objects from.
- A
Rectangleis created like this:Rectangle myRect = new Rectangle(width, height); - It has an instance method
getArea()that returns the area as anint. - It has an instance method
getPerimeter()that returns the perimeter as anint.
Your Task: Write Java code that creates a Rectangle object with a width of 10 and a height of 25. Then, call its methods to calculate and print its area and perimeter to the console.
Practice 2: Predict the Crash
Read the following code snippet. What will be printed to the console? Or will the program crash? If it crashes, on which line and why?
String city = "Atlanta";
String state = null;
System.out.println(city.toLowerCase());
System.out.println(state.toLowerCase());
System.out.println("Done!");
Practice — 8 questions
In simple terms, calling an instance method is like asking a specific object, like your phone, to do something it knows how to do, like "play a song" or "get the time."
// 1. Create a String object
String teamName = "Seattle Seahawks";
// 2. Call the length() method on the teamName object
int len = teamName.length(); // len is now 16
[[fig:string_method_trace]]
// 3. Call the toUpperCase() method on the teamName object
String loudName = teamName.toUpperCase(); // loudName is now "SEATTLE SEAHAWKS"
- 1.14.A: Develop code to call instance methods and determine the result of these calls.
- 1.14.A.1
- Instance methods are called on objects of the class. The dot operator is used along with the object name to call instance methods.
- 1.14.A.2
- A method call on a null reference will result in a NullPointerException.
flowchart TD
A[Start] --> B{Is object reference null?};
B -->|No| C[Call method using dot operator: object.method()];
C --> D[Method executes];
D --> E[Program continues];
B -->|Yes| F(NullPointerException);
F --> G[Program crashes];
Read what Saavi narrates
Hello there, I'm Saavi. Welcome to Shrutam.
Let's talk about how we get things done in our programs.
Imagine you're at a busy coffee shop. You don't just shout "make a latte" into the room. That would be chaos. Instead, you walk up to a specific barista, get their attention, and make your request. You've targeted your command to an "object"—the barista—who knows how to perform the action.
In Java, we do the exact same thing. We call methods on specific objects. Today, we're learning the syntax for that. It's all about telling objects to perform actions they know how to do. The key is using a special symbol, the dot, to connect an object to a command it understands.
Think of it like a TV remote. The TV is your object. The remote has buttons like power, volume up, and so on. The dot in Java is like pointing the remote at the TV and pressing a button. You write the object's name, then a dot, then the method name with parentheses. For example, if you have a string variable called 'greeting', you could find its length by writing 'greeting dot length parentheses'.
Let's walk through a quick example. Imagine we have a string variable called 'fullName' which holds the name "Priya Sharma".
If we want to know how many characters are in that name, we can call the length method on it. We'd write 'int charCount equals fullName dot length parentheses'. The 'charCount' variable would now hold the number twelve.
If we wanted an all-caps version, we could write 'String shoutedName equals fullName dot toUpperCase parentheses'. The 'shoutedName' variable would then hold a brand new string: "PRIYA SHARMA".
See how that works? We're telling the 'fullName' object to do things for us.
Now, here's one of the most common mistakes every new programmer makes. What happens if your variable doesn't actually point to an object? In Java, we call this 'null'. It's like having a remote but no TV. If you try to press a button, what happens? Your program crashes. This is called a Null Pointer Exception. It's the computer telling you, "You asked me to do something, but you never told me what to do it to!"
Spotting this error is a huge step forward. You're not just writing code; you're learning to anticipate problems. You're building the instincts of a real programmer. Keep practicing, and don't be afraid of those error messages. They're just clues on your journey. You've got this.
`length()` is an *instance* method. It needs to know *which string's* length you want. You can't ask the blueprint for the length of a specific car.
Call the method on an object (an instance) of the class.
String myWord = "Boston";
int len = myWord.length(); // Correct!
The parentheses are what tell Java to *execute* the method. Without them, Java thinks you're trying to access a field or variable named `toUpperCase`, which doesn't exist, causing a compiler error.
Always include parentheses, even if they're empty.
String upper = myWord.toUpperCase(); // Correct!
Many methods, especially on immutable objects like `String`, don't change the original object. They create and *return* a new one with the changes. If you don't save that new object, it's lost forever.
Assign the result of the method call to a variable.
String name = "Carlos";
String loudName = name.toUpperCase(); // Save the returned value
System.out.println(loudName); // Prints "CARLOS"
If `findUserInput()` returns `null`, the next line will cause a `NullPointerException`. You made an unsafe assumption.
Before calling methods, check if the object is `null`. (We'll cover `if` statements soon, which are the formal way to do this). For now, be aware of the danger.
// Potentially crashes
String input = findUserInput(); // This method might return null
int len = input.length(); // Uh oh...