AP Computer Science A · Study guide

Calling Instance Methods

AP® Computer Science A · Using Objects and Methods

Calling Instance Methods

How to ask an object to do something: the dot operator, how instance methods use and change an object's own data, how to use their return values, and why calling a method through null fails.

Big Picture

Instance methods are called on objects of the class. They work with the data stored in the particular object they are called on, so the same method can give different results for different objects. The dot operator is used along with the object name to call them: bottle.drink(250). Some instance methods change the object's state; others report information about it through a return value. Because an instance method needs an object, calling one through a null reference results in a NullPointerException.

1Methods That Belong to Objects

An object combines data with the behaviors that use that data. A Bottle object stores its capacity and the amount of water in it, and its instance methods, fill, drink, getAmount, spaceLeft, and isEmpty, read or change those values. An instance method's header has no static keyword, which signals that it needs an object to work on.

When a program has several objects of the same class, each call must say which object should act. a.drink(200) asks the bottle referred to by a to drink; the bottle referred to by b is not involved. This is what makes objects useful: the class defines the behavior once, and each object applies it to its own data.

You have used instance methods since the first String: word.length() asks a particular string for its length. Every class you meet, whether from the library or written by a teammate, works the same way.

Figure 1. Instance methods are called on objects of the class. Each object has its own attributes, so the same method call changes only the object it is called on.
Kind of instance methodExampleHow the call is used
void (changes state)bottle.drink(120);A statement by itself
Returns a numberbottle.getAmount()Stored, printed, or used in arithmetic
Returns a booleanbottle.isEmpty()Printed or used in a condition
Returns an objectword.substring(4)Stored, printed, or used to call another method

2The Dot Operator

The dot operator is used along with the object name to call instance methods. The general form is objectReference.methodName(arguments). The expression before the dot must evaluate to a reference to an object; it is usually a variable name, but it can be any expression that produces an object, including another method call that returns an object.

After the dot comes the method name and the argument list in parentheses, which follow the same rules as any method call: the arguments must match the method's parameter list in number, order, and type. Parentheses are required even when there are no arguments, as in bottle.fill(); leaving them off does not call the method.

Figure 2. The dot operator is used along with the object name to call instance methods. The method acts on the object the reference refers to.
Worked Example 1 Calls on returned objects

Calling a Method on the Result of Another

When a method returns an object, another method can be called on that result. Predict the output.

Code
String word = "telescope";
System.out.println(word.substring(4));
System.out.println(word.substring(4).length());
System.out.println(word.substring(4).indexOf("o"));
System.out.println(word);
Output
scope
5
2
telescope
  1. 1word.substring(4) returns a new String, "scope".
  2. 2Chaining. .length() is then called on "scope": 5.
  3. 3.indexOf("o") on "scope" finds "o" at index 2.
  4. 4The original is unchanged. word still refers to "telescope"; each substring call built a new string.
Result: The output is scope, 5, 2, and telescope. Calls are evaluated left to right, each one acting on the object returned by the call before it.
Common Mistake 1 · Forgetting the Parentheses

bottle.getAmount without parentheses is not a method call and does not compile in an expression such as int x = bottle.getAmount;. Every call needs parentheses, even when the method takes no arguments.

3Changing an Object's State

Many instance methods exist to change the object they are called on. fill() sets the amount to the capacity; drink(120) lowers it by 120. Such methods are often void: they return nothing, and their whole purpose is the change they make. A call to a void method is a statement by itself.

Because the object keeps its state between calls, a sequence of calls builds on itself. Tracing such code means keeping track of each object's attributes and updating them after every call, as in the table below. Methods may also have preconditions: drink expects that the bottle holds at least the amount requested, and it is the caller's job to respect that.

StatementamountValue printed
Bottle bottle = new Bottle(500);0
bottle.fill();500
bottle.drink(120);380
bottle.drink(80);300
println(bottle.getAmount());300300
println(bottle.spaceLeft());300200
Worked Example 2 Sequences of calls

Tracing an Object Through Several Calls

The Bottle class is given. Predict the output.

The Bottle class and a short program
public class Bottle
{
    private int capacity;
    private int amount;

    public Bottle(int cap)
    {
        capacity = cap;
        amount = 0;
    }

    public void fill()
    {
        amount = capacity;
    }

    /** Precondition: ml <= the amount currently in the bottle */
    public void drink(int ml)
    {
        amount = amount - ml;
    }

    public int getAmount()
    {
        return amount;
    }

    public int spaceLeft()
    {
        return capacity - amount;
    }

    public boolean isEmpty()
    {
        return amount == 0;
    }
}
Output
300
200
  1. 1Construction. Capacity 500, amount 0.
  2. 2fill(). Amount becomes 500.
  3. 3Two drink calls. 500 − 120 = 380, then 380 − 80 = 300.
  4. 4Getters. getAmount() returns 300; spaceLeft() returns 500 − 300 = 200.
Result: The output is 300 and 200. Each call acts on the same object, so its state carries over from one call to the next.
Common Mistake 2 · Losing Track of Earlier Calls

An object remembers what earlier calls did. After fill() and two drink calls, the amount reflects all three. When predicting output, update the object's state after every call, in order, rather than reasoning about each call on its own.

4Using Return Values

Non-void instance methods return information about the object. getAmount() returns an int, isEmpty() returns a boolean, and a String's substring returns a new String. As with any non-void method, the result must be stored in a variable or used as part of an expression to be useful.

Methods that only report information, often named with get or is, usually leave the object unchanged, so calling them several times gives the same answer until some other method changes the state. Calling one as a statement by itself compiles, but the returned value is discarded and the line accomplishes nothing.

Worked Example 3 Return values

Using Results From Instance Methods

Predict the output.

Using the same Bottle class
public class Bottle
{
    private int capacity;
    private int amount;

    public Bottle(int cap)
    {
        capacity = cap;
        amount = 0;
    }

    public void fill()
    {
        amount = capacity;
    }

    /** Precondition: ml <= the amount currently in the bottle */
    public void drink(int ml)
    {
        amount = amount - ml;
    }

    public int getAmount()
    {
        return amount;
    }

    public int spaceLeft()
    {
        return capacity - amount;
    }

    public boolean isEmpty()
    {
        return amount == 0;
    }
}
Output
1050
400
  1. 1After the calls, a holds 300 and b holds 750 (Figure 1).
  2. 2Combining return values. a.getAmount() + b.getAmount() is 300 + 750 = 1050.
  3. 3A call inside arithmetic. a.spaceLeft() is 200, so the expression is 400.
Result: The output is 1050 and 400. A call to a non-void instance method is an expression whose value can be stored or used in further calculation.
Worked Example 4 boolean methods

Asking an Object a Yes-or-No Question

Predict the output.

Using the same Bottle class
public class Bottle
{
    private int capacity;
    private int amount;

    public Bottle(int cap)
    {
        capacity = cap;
        amount = 0;
    }

    public void fill()
    {
        amount = capacity;
    }

    /** Precondition: ml <= the amount currently in the bottle */
    public void drink(int ml)
    {
        amount = amount - ml;
    }

    public int getAmount()
    {
        return amount;
    }

    public int spaceLeft()
    {
        return capacity - amount;
    }

    public boolean isEmpty()
    {
        return amount == 0;
    }
}
Output
true
false
true 0
  1. 1New bottle. Amount 0, so isEmpty() returns true.
  2. 2After fill(). Amount 250: false.
  3. 3After drinking 250. Amount 0 again: true, and the getter confirms 0.
Result: The output is true, false, and true 0. Methods that return boolean report facts about an object's current state.
Worked Example 5 Unused results

A Call Whose Result Is Thrown Away

Predict the output. Which line has no visible effect?

Using the same Bottle class
public class Bottle
{
    private int capacity;
    private int amount;

    public Bottle(int cap)
    {
        capacity = cap;
        amount = 0;
    }

    public void fill()
    {
        amount = capacity;
    }

    /** Precondition: ml <= the amount currently in the bottle */
    public void drink(int ml)
    {
        amount = amount - ml;
    }

    public int getAmount()
    {
        return amount;
    }

    public int spaceLeft()
    {
        return capacity - amount;
    }

    public boolean isEmpty()
    {
        return amount == 0;
    }
}
Output
600
  1. 1jug.spaceLeft(); computes 0 and returns it, but nothing stores or prints it, and the method does not change the bottle. The line has no effect.
  2. 2jug.drink(400); is a void method that changes the object's state: 1000 − 400 = 600.
  3. 3The difference. Calling a void method as a statement is normal, because its purpose is its effect. Calling a non-void method as a statement throws its result away.
Result: The program prints 600. To use a non-void method, store its result or use it in an expression; on its own, the call computes a value and discards it.

5Instance Methods Versus Class Methods

The expression before the dot tells you which kind of method is being called. Class methods, marked static, are called with the class name, as in Math.sqrt(49), because they do not depend on any object. Instance methods are called with an object reference, as in bottle.getAmount(), because their result depends on that object's data.

Mixing these up causes compile errors. Bottle.getAmount() fails because no bottle is specified; Java reports that a non-static method cannot be referenced from a static context. When reading documentation, check each method header for static to decide how to call it.

Figure 3. Before the dot: a class name for a class method, an object reference for an instance method.
Worked Example 6 Calling without an object

Using the Class Name for an Instance Method

Explain the compile error.

Code that does not compile
public class Bottle
{
    private int capacity;
    private int amount;

    public Bottle(int cap)
    {
        capacity = cap;
        amount = 0;
    }

    public void fill()
    {
        amount = capacity;
    }

    /** Precondition: ml <= the amount currently in the bottle */
    public void drink(int ml)
    {
        amount = amount - ml;
    }

    public int getAmount()
    {
        return amount;
    }

    public int spaceLeft()
    {
        return capacity - amount;
    }

    public boolean isEmpty()
    {
        return amount == 0;
    }
}
  1. 1getAmount is an instance method. It has no static keyword, and its answer depends on a particular bottle.
  2. 2Bottle.getAmount() names no bottle. Java cannot know whose amount to return, so it reports that a non-static method cannot be referenced from a static context.
  3. 3Fix. Call it on an object: bottle.getAmount().
Result: The compiler rejects the call. Instance methods need an object before the dot; only class methods are called with the class name.
Common Mistake 3 · Calling an Instance Method With the Class Name

String.length() and Bottle.getAmount() do not compile: there is no particular string or bottle to ask. Create or obtain an object first, then call the method on it: word.length(), bottle.getAmount().

6Calling a Method Through null

A method call on a null reference will result in a NullPointerException. The compiler cannot detect this in advance, because whether a variable holds null is known only when the program runs. The program compiles, runs normally until the call, and then stops.

Common causes include declaring a variable without creating an object, setting a variable to null earlier and forgetting, or using a method's result that turned out to be null. The remedy is always the same: make sure the reference refers to an actual object before calling methods through it.

Figure 4. A method call on a null reference will result in a NullPointerException.
CallResult
bottle.getAmount() where bottle refers to an objectRuns on that object
Bottle.getAmount()Compile-time error: instance method needs an object
spare.getAmount() where spare is nullNullPointerException at run time
Math.sqrt(49)Class method: called with the class name
Worked Example 7 NullPointerException

Calling a Method on a null Reference

What happens when this program runs?

Using the same Bottle class
public class Bottle
{
    private int capacity;
    private int amount;

    public Bottle(int cap)
    {
        capacity = cap;
        amount = 0;
    }

    public void fill()
    {
        amount = capacity;
    }

    /** Precondition: ml <= the amount currently in the bottle */
    public void drink(int ml)
    {
        amount = amount - ml;
    }

    public int getAmount()
    {
        return amount;
    }

    public int spaceLeft()
    {
        return capacity - amount;
    }

    public boolean isEmpty()
    {
        return amount == 0;
    }
}
  1. 1The code compiles. spare has type Bottle, and Bottle has a fill method.
  2. 2The first line prints.
  3. 3spare.fill() fails. spare holds null, so there is no bottle to fill. Java throws a NullPointerException, and the last line never runs.
  4. 4Fix. Create the object first: Bottle spare = new Bottle(500);.
Result: The program prints checking the spare, then stops with a NullPointerException. A method call on a null reference always fails at run time.
Common Mistake 4 · Assuming Compiled Code Cannot Fail

Code that calls a method through a null reference compiles without complaint. The NullPointerException appears only at run time. When tracing, check that every variable before a dot actually refers to an object at that moment.

Four Habits for Instance Methods

1. Object, Dot, Method

The reference before the dot chooses which object acts.

2. Track State

Each call starts from the state earlier calls left behind.

3. Use Every Result

Store or use what non-void methods return.

4. No Calls Through null

A null reference before the dot means a NullPointerException.

Core Synthesis

Instance methods are called on objects of the class. The dot operator is used along with the object name to call instance methods, and each call works with the attributes of the object it is called on, either changing them or reporting information through a return value that must be stored or used. Instance methods cannot be called with the class name alone, and a method call on a null reference will result in a NullPointerException.