Topic 1.14 — Calling Instance Methods

Goal: call methods on objects (instance methods), match calls to method signatures, and use return values correctly.

The big idea

An instance method belongs to an object (an instance), not the class itself. You call it using an object reference, a dot, and the method name.

Pattern: objectRef.methodName(arguments)

Compare: class vs. instance calls

  • Class method: Math.random() (uses class name)
  • Instance method: str.length() (uses object variable)

Common instance method example: String

You’ve already been using objects like String. Strings have instance methods.

String s = "computer";

int n = s.length();          // returns an int
String t = s.substring(0, 3); // returns a String ("com")

Match calls to signatures

The method signature tells you how to call it (name + parameter types/order) and what it returns.

// Example signatures (from String):
int length()
String substring(int beginIndex, int endIndex)

// Matching calls:
int a = s.length();
String b = s.substring(1, 4);

Return values: store or use

If it returns something, you can store it or use it inside a bigger expression.

// store
int len = s.length();

// use directly
if (s.length() > 5) {
  // ...
}

Common mistake: calling an instance method like a class method

Instance methods need an object reference.

// Correct:
String s = "hi";
int n = s.length();

// Not correct (length is not a String class method):
int m = String.length();

Another common mistake: wrong parameter order

Order matters. Types matter. Count matters.

// substring(beginIndex, endIndex)
String sub = s.substring(2, 5);  // ✅

// Wrong order would change meaning (or not compile if types differ)
String sub2 = s.substring(5, 2); // 🚫 (logic error / invalid range)

null reference (preview)

If a reference is null, there is no object to call a method on.

String s = null;
// s.length();  // would cause an error

You’ll learn to avoid this later, but it’s important to know that instance methods require a real object.

Exam mindset

  • Instance methods use objectRef., not the class name.
  • Match the call to the method signature (name + parameters).
  • Return type tells you what kind of value you get back.
  • Be careful with parameter order and ranges (especially with strings).

Quick self-check

  1. What is the general pattern for calling an instance method?
  2. What does s.length() return?
  3. What does s.substring(1, 4) return?
  4. Why can’t you call an instance method without an object?
  5. What parts of a signature matter when calling a method?

← Back to Unit 1 topics