AP CSA – 1.14 Calling Instance Methods


1. What Is an Instance Method?

An instance method is a method that belongs to an object created from a class. To use an instance method, you must have an object reference.

Syntax:

objectName.methodName(arguments);

2. Instance Methods vs. Static Methods

Instance Methods Static Methods
Called on an object Called on the class
Access instance variables Cannot access instance variables directly
Use obj.method() Use ClassName.method()

Static method example:

Math.sqrt(16);

Instance method example:

str.length();

3. Calling Methods on a String Object

String str = "Hello";
int len = str.length();

Other common String instance methods:

str.toUpperCase();     // "HELLO"
str.substring(1, 4);   // "ell"
str.indexOf("l");      // 2

4. Calling Instance Methods on Custom Objects

Example class:

public class Dog {
    private int age;

    public void setAge(int a) {
        age = a;
    }

    public int getAge() {
        return age;
    }
}

Using the class:

Dog d = new Dog();
d.setAge(5);
int a = d.getAge();

5. Dot Notation

Dot notation is used for all instance method calls:

objectReference.methodName(parameters);

Examples:

student.getName();
car.startEngine();
scanner.nextInt();

6. Methods That Return Values vs. Methods That Don’t

Methods that return values:

int len = str.length();
String upper = str.toUpperCase();

Void methods (do not return values):

Dog d = new Dog();
d.setAge(3);

7. Chaining Instance Method Calls

String result = str.toUpperCase().substring(1, 3);

This calls multiple instance methods in a row.


8. Common Mistakes

String s = null;
s.length();   // ERROR: NullPointerException
Scanner sc;
int x = sc.nextInt();  // ERROR: sc not initialized
Math.random();  // correct
myRandom.random();  // incorrect unless myRandom is an object with that method

9. Why This Matters in AP CSA


10. Quick Summary