AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/1/1-14)
Unit 1 · Topic 1.14
1.14 Calling Instance Methods
Instance methods are the behaviors of an object, and you call them on a particular object with the dot operator. This topic is about tracing those calls, keeping track of which object each call changes, and recognizing the NullPointerException you get when there's no object at all.
Key terms
- instance method
- dot operator
NullPointerException
Calling an instance method
An instance method belongs to the objects of a class rather than to the class itself, so it has no static in its header. You call it on a specific object: the variable name, a dot, the method name and the arguments.
String word = "planet";
int n = word.length();
System.out.println(n);
length() is an instance method of String. It's called on the object word refers to and works with that object's characters, so it returns 6.
All the rules from 1.9 apply: the arguments must match the parameters, a void method can't be used in an expression, and a non-void method's return value should be stored or used.
Each object has its own state
An instance method works with the data of the object it's called on. If you have two objects of the same class, calling a method on one doesn't affect the other.
Below, a Wallet class has a constructor Wallet(int start), void spend(int amount), void earn(int amount) and int getDollars(). mine.spend(8) changes only the wallet mine refers to.
This is different from class methods (1.10), which aren't tied to any object. Instance methods always need an object.
Return values and chained calls
Instance methods often come in two flavors. Some return information about the object without changing it, like getDollars(). Others change the object and return nothing, like spend(8). (In Unit 3 you'll call these accessor and mutator methods.)
A returned value can go straight into another call. In yours.earn(mine.getDollars()), Java first runs the inner call, mine.getDollars(), then passes its result as the argument to earn. Work from the inside out when you trace.
When a call returns an object, you can call a method on the result right away. For example, word.substring(1).length() takes a substring of word and then asks that new string for its length. Each dot is one call, done left to right.
NullPointerException
If a reference variable holds null, there's no object to call the method on. The code still compiles, because the compiler only checks that the variable's type has that method. But when the call runs, Java throws a NullPointerException and the program stops.
Wallet w = null;
System.out.println("checking");
System.out.println(w.getDollars());
This prints checking, then throws a NullPointerException on the third line.
On free-response questions, null usually shows up as an empty spot, like an empty seat in a 2D array of Student objects. Check if (seat != null) before calling a method on it (you'll learn != in 2.2).
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Tracing two objects
Using the
Walletclass described above, what does this code print?Wallet mine = new Wallet(20); Wallet yours = new Wallet(5); mine.spend(8); yours.earn(mine.getDollars()); System.out.println(mine.getDollars() + " " + yours.getDollars());Show the solutionHide the solution
- Step 1:
minestarts with 20 dollars andyourswith 5. They are two separate objects. - Step 2:
mine.spend(8)changesmineonly: 20 − 8 = 12. - Step 3:
yours.earn(mine.getDollars()): firstmine.getDollars()returns 12. Thenyours.earn(12)adds 12 toyours: 5 + 12 = 17.mineis unchanged. - Step 4: The print joins 12, a space and 17.
Answer: It prints
12 17. - Step 1:
Common mistakes
- Calling an instance method with the class name, like
Wallet.getDollars(). Instance methods need an object:mine.getDollars(). - Assuming a method call on one object changes another object of the same class. Only aliases (two variables for one object) share changes.
- Thinking a
NullPointerExceptionis a compile error. It happens at run time, when the call onnullactually executes.
On the exam
- Many questions trace several method calls on a few objects. Keep a small table with one row per object and update it after each call.
- When a question involves objects that might be missing, look for the case where a variable is
null. Calling a method on it is the classic run-time error.
Connected topics
Videos
Check yourself
2 questions on 1.14 Calling Instance Methods. Pick an answer to see if you got it, and why.
Consider the following code segment.String word = "planet";
int n = word.length();
String part = word.substring(n - 3);
System.out.println(n + part);What is printed as a result of executing the code segment?
Consider the following class.public class Lamp
{
private int level;
public Lamp()
{
level = 1;
System.out.print("A");
}
public Lamp(int start)
{
level = start;
System.out.print("B");
}
public void brighten()
{
level++;
System.out.print(level);
}
}What is printed as a result of executing the following code segment?Lamp x = new Lamp(5);
Lamp y = new Lamp();
y.brighten();
x.brighten();
0 of 2 answered