Unit 1 · 12 min

1.14 Calling Instance Methods

Instance methods act on one particular object.

Summary, objectives and course and exam description (CED) codes

Instance methods are called on objects of the class, using the object's name and the dot operator, as in p.grow(5). They act on that one object. Calling a method on a null reference throws a NullPointerException.

By the end of this session you can

  • 1.14.A Develop code to call instance methods and determine the result of these calls.

1.14.A1.14.A.11.14.A.2

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. Calling instance methods with the dot operator

Instance methods are called on objects of the class. The dot operator is used with the object name to call an instance method 1.14.A.1. The method acts on that one object.

This continues the topic 1.13 example: p refers to a Plant named "Fern" with height 30, and q refers to a Plant named "Mint" with height 0.

Plant p = new Plant("Fern", 30);
Plant q = new Plant("Mint");
p.grow(5);                         // void: a statement on its own
System.out.println(p.getHeight()); // 35
System.out.println(q.getName() + " " + q.getHeight()); // Mint 0

Output:

35
Mint 0

p.grow(5) changed only the object p refers to. q still has height 0.

An instance method needs an object, so calling it with the class name does not compile:

// does not compile
Plant.grow(5);

Real view:

error: non-static method grow(int) cannot be referenced from a static context

2. NullPointerException

A method call on a null reference results in a NullPointerException 1.14.A.2. The code compiles, but the program stops when the call runs.

Plant r = null;                    // r refers to no object
System.out.println("Checking r");
System.out.println(r.getHeight());
System.out.println("Done");

Output:

Checking r
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Plant.getHeight()" because "r" is null

Done is never printed: the exception interrupts the normal flow of the program (topic 1.1). The exact wording after the colon can differ between Java versions; the exception name is what matters.

Watch out: printing a null variable, as in System.out.println(r);, is fine and prints null. Only calling a method on it throws the exception.

3. Aliases: two names, one object

After Plant b = a;, both variables refer to the SAME object. Calling an instance method through either name changes that one object.

Plant a = new Plant("Basil", 10);
Plant b = a;
b.grow(5);
a.grow(3);
System.out.println(a.getHeight() + " " + b.getHeight());

Output:

18 18

10 + 5 + 3 is 18, and both names report it, because there is only one Plant. (Unit 3 studies aliasing in more depth.)

4. Looking ahead to Unit 3: inside a non-void method

Inside a class, a method’s statements can use the object’s attributes directly, and a return statement sends one value back to the caller and ends the method. The value must match the return type in the header. This is what the free-response practice for this unit asks you to write.

public class Plant
{
    private String name;
    private int height;

    public Plant(String n, int h)
    {
        name = n;
        height = h;
    }

    // inside the Plant class
    public String getInitial()
    {
        return name.substring(0, 1);
    }
}

// in main
Plant p = new Plant("Fern", 30);
String first = p.getInitial();
System.out.println(first);

Output:

F

If p refers to a Plant named "Fern", p.getInitial() returns "F". A method returns a value; it does not print it. The caller decides what to do with the value.

Lock it in: memory hooks

  • Instance method callobject dot method: tell one particular object what to do.
  • nullYou cannot ask nobody to do something: a call on null throws a NullPointerException.

Common misconceptions

  • "You can call an instance method with the class name, like Plant.grow(5)."

    Not quite. An instance method needs an object. Plant.grow(5) does not compile; p.grow(5) works, where p refers to a Plant object.

  • "Calling a method on null returns null or 0."

    Not quite. It throws a NullPointerException at run time and the program stops. The code compiles, because the compiler does not know the variable will be null.

  • "After Plant b = a; there are two plants."

    Not quite. There is one Plant object and two references to it. A change made through b is seen through a.

Exam traps

  • Aliasing: after Plant b = a; both variables refer to the SAME object, so b.grow(5) changes what a.getHeight() returns too.
  • Printing a null variable prints null, but calling a method on it throws a NullPointerException.
  • A void instance method, such as grow, is a statement on its own; a non-void one, such as getHeight, gives a value to store or use.

2PracticeRecall it, then check yourself

In 30 seconds

  1. Instance methods are called on objects of the class.
  2. Use the object's name and the dot operator: p.grow(5).
  3. Plant.grow(5) does not compile, because an instance method needs an object.
  4. A method call on a null reference throws a NullPointerException.
  5. Aliases (two variables referring to the same object) see the same changes.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 4 questions

Checkpoint: Calling Instance Methods

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. Plant class (implementations not shown)
    Constructor or methodWhat it does
    public Plant(String n)Sets the name to n and the height to 0
    public Plant(String n, int h)Sets the name to n and the height to h
    public String getName()Returns the name
    public int getHeight()Returns the height
    public void grow(int cm)Adds cm to the height
    1 Consider the following code segment. What is printed? 1.14.A.1
    Plant a = new Plant("Basil", 10);
    Plant b = a;
    b.grow(5);
    a.grow(3);
    System.out.println(a.getHeight() + " "
                       + b.getHeight());
    Show answer

    Answer: C. a and b refer to the same object: 10 + 5 + 3 = 18 for both. A and B treat b as a separate copy. D ignores the call a.grow(3) and also treats b as a copy.

  2. Plant class (implementations not shown)
    Constructor or methodWhat it does
    public Plant(String n)Sets the name to n and the height to 0
    public Plant(String n, int h)Sets the name to n and the height to h
    public String getName()Returns the name
    public int getHeight()Returns the height
    public void grow(int cm)Adds cm to the height
    2 What happens when this code segment runs? 1.14.A.2
    Plant s = new Plant("Sage");
    s = null;
    System.out.println(s.getName());
    Show answer

    Answer: D. s is null, so calling getName on it throws a NullPointerException at run time. A is wrong because s no longer refers to the Sage object. B would only happen if s itself were printed. C is wrong because the compiler does not know s will be null.

  3. Plant class (implementations not shown)
    Constructor or methodWhat it does
    public Plant(String n)Sets the name to n and the height to 0
    public Plant(String n, int h)Sets the name to n and the height to h
    public String getName()Returns the name
    public int getHeight()Returns the height
    public void grow(int cm)Adds cm to the height
    3 Consider the following code segment. What is printed? 1.14.A.1
    Plant p = new Plant("Rose", 25);
    Plant q = new Plant("Lily");
    q.grow(p.getHeight());
    p.grow(5);
    System.out.println(p.getHeight() + " " + q.getHeight());
    Show answer

    Answer: A. q starts at 0 and grows by 25 (the value p.getHeight() returned at that moment). Then p grows to 30. B treats q as linked to p, but they are separate objects. C forgets p.grow(5). D forgets that q.grow used the returned height.

  4. Plant class (implementations not shown)
    Constructor or methodWhat it does
    public Plant(String n)Sets the name to n and the height to 0
    public Plant(String n, int h)Sets the name to n and the height to h
    public String getName()Returns the name
    public int getHeight()Returns the height
    public void grow(int cm)Adds cm to the height
    4 Assume Plant p = new Plant("Fern", 30); has run. Which of the following statements compiles? 1.14.A.1
    Show answer

    Answer: B. An instance method is called on an object with the dot operator, and getHeight returns an int that can be stored. A calls an instance method with the class name. C uses a void method inside an expression. D leaves out the parentheses of the method call and tries to assign to it.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Instance methodtap to flip

    A method called on an object of the class, using the object's name and the dot operator.

    Example and CED codes
  • Dot operatortap to flip

    The . used to call a method on an object (p.grow(5)) or a class method with the class name (Math.abs(-3)).

    Example and CED codes
  • NullPointerExceptiontap to flip

    The exception thrown when a method is called on a null reference.

    Example and CED codes
  • nulltap to flip

    A special literal meaning a reference variable is not associated with any object.

    Example and CED codes
  • Object referencetap to flip

    The value a reference variable holds: it can be thought of as the memory address of the object.

    Example and CED codes
  • Objecttap to flip

    A specific instance of a class with defined attributes.

    Example and CED codes
  • Methodtap to flip

    A named block of code that only runs when it is called.

    Example and CED codes

Questions students ask

What is an instance method in Java?

An instance method is a method called on an object of the class. It works with that object's attributes. You call it with the object's name and the dot operator, such as p.getHeight().

What is the difference between an instance method and a class method?

An instance method is called on an object (p.grow(5)) and has no static keyword. A class method has static in its header and is called with the class name (Math.sqrt(9.0)).

What causes a NullPointerException?

Calling a method on a reference variable that holds null. There is no object to run the method on, so the program throws a NullPointerException at run time.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure