AP COMPUTER SCIENCE A • USING OBJECTS AND METHODS

Calling Instance Methods

Learn how objects communicate and perform actions through method invocation in Java.

Historical Context & Motivation

The idea that software should be organized around objects — self-contained units that bundle data with the operations that act on that data — was one of the most influential breakthroughs in the history of programming. Before object-oriented programming (OOP), large codebases were written in procedural languages like C and Fortran, where data structures and the functions that manipulated them were entirely separate. As software systems grew in complexity during the 1960s and 1970s, programmers found it increasingly difficult to track which functions should be applied to which data, leading to tangled, error-prone code. The concept of instance methods — functions that belong to a specific object and operate on its internal state — emerged as the core mechanism by which objects communicate, transforming how developers reason about program design.

1967
Simula 67
Ole-Johan Dahl and Kristen Nygaard released Simula 67, the first language to introduce classes and objects, establishing the paradigm of sending messages (calling methods) on object instances.
1972
Smalltalk
Alan Kay's Smalltalk popularized the "message passing" metaphor: every computation is an object receiving a message, which is fundamentally equivalent to calling an instance method.
1983
C++ Introduced
Bjarne Stroustrup created C++ by adding classes and member functions to C, bringing instance methods into mainstream systems programming and inspiring Java's syntax.
1995
Java Released
Sun Microsystems released Java, adopting the dot-notation syntax for calling instance methods (e.g., object.method()) that AP Computer Science A students use today.
2003
AP CS A Adopts Java
The College Board transitioned the AP Computer Science A exam from C++ to Java, making calling instance methods using the dot operator a foundational skill tested every year.

This historical trajectory reveals a persistent question at the heart of software engineering: how should a program ask an object to perform work or reveal information about itself? The answer, refined across decades, is the instance method call — a precise syntax that identifies which object to act upon, which behavior to invoke, and what data to supply. Mastering this syntax is essential not only for the AP exam but for every Java program you will ever write.

Core Principles & Definitions

Before you can call an instance method, you need a clear mental model of what objects and methods are and how they relate. An object is a specific instance of a class, created at runtime with the new keyword. Each object encapsulates its own set of instance variables (also called fields or attributes) that store its state. An instance method is a non-static method defined within the class; it operates on the specific object through which it is called. The following principles capture the core ideas you must internalize.

1

Dot Operator Syntax

An instance method is invoked using the pattern objectReference.methodName(arguments). The dot operator (.) binds the method call to a specific object.
2

Method Signature

A method's signature consists of its name and parameter list. The signature determines which method the compiler selects when overloaded methods exist.
3

Return Type

Methods may return a value (int, double, String, an object, etc.) or return nothing (void). A non-void method call is an expression that evaluates to the returned value.
4

Accessor vs. Mutator

Accessor methods (getters) return information about the object's state without changing it. Mutator methods (setters) modify the object's internal state.
5

Pass by Value

Java passes all arguments by value. For primitives, a copy of the value is passed. For objects, a copy of the reference is passed — the method receives the same pointer to the object on the heap.
KEY TAKEAWAY
Think of an object as a remote-controlled robot and an instance method as a specific button on its remote. Pressing the button (calling the method) tells that particular robot to perform an action or report a reading. Different robots (objects) of the same model (class) each respond independently because they carry their own sensors and motors (instance variables). The dot operator is how you aim the remote at a specific robot: myRobot.moveForward(3) instructs myRobot — not some other robot — to advance three steps.

Visual Explanation

The diagram below illustrates the anatomy of an instance method call and how control flows between the calling code and the object. Understanding this flow is critical for tracing code on the AP exam, where you must mentally execute method calls to predict program output.

The highlighted line int len = s.length(); demonstrates all five components of an instance method call: the object reference (s), the dot operator, the method name (length), the argument list (empty in this case), and the capture of the returned value.

Notice that the calling code does not need to know how the length() method computes its result — it only needs to know the method's name, required parameters, and return type. This principle is called abstraction, and it is one of the cornerstones of object-oriented design. On the AP exam, you will frequently encounter classes whose internal implementation is hidden; you are expected to call their methods correctly based solely on their documented signatures and return types.

How Instance Method Calls Work

The Syntax Blueprint

GENERAL FORM — NON-VOID METHOD
ReturnType variable = objectRef.methodName(arg₁, arg₂, …, argₙ);
ReturnType — the data type of the value the method returns (e.g., int, String, boolean). objectRef — a variable holding a reference to the object. methodName — the exact name as declared in the class. arg₁ … argₙ — actual arguments whose types must match the formal parameters in order.
GENERAL FORM — VOID METHOD
objectRef.methodName(arg₁, arg₂, …, argₙ);
A void method performs an action (mutates state, prints output, etc.) but does not return a value. It cannot appear on the right side of an assignment or inside an expression.

Execution Flow in Detail

When the Java runtime encounters an instance method call, it performs several steps in sequence. First, the object reference is evaluated — if it is null, a NullPointerException is thrown immediately. Second, the arguments in the parentheses are evaluated left to right, and their values are copied into the method's formal parameters (pass by value). Third, control transfers to the body of the method, which executes using the object's own instance variables. Finally, when the method reaches a return statement (or the closing brace for void methods), control returns to the caller, and the returned value replaces the method call expression.

Method Chaining

Because a non-void method call evaluates to a value, that value can itself be the target of another method call. This pattern, known as method chaining, appears frequently on the AP exam. For example, str.substring(1, 4).toUpperCase() first calls substring on str, which returns a new String, and then calls toUpperCase() on that intermediate String. To trace chained calls, evaluate from left to right, replacing each call with its return value before proceeding to the next.

💡 AP EXAM TIP
The AP exam frequently uses method calls as arguments to other methods, e.g., System.out.println(s.indexOf("a")). Evaluate the innermost method call first and substitute its return value before evaluating the outer call.

Classifying Instance Methods

Instance methods fall into distinct categories based on whether they read or modify the object's state and whether they accept parameters. Recognizing these categories helps you predict what a method does and how to use its return value — a skill tested heavily on the AP exam's multiple-choice section. The diagram below organizes the most common categories you will encounter.

This classification tree shows how instance methods divide into accessors and mutators, each of which may or may not accept parameters. Note that some methods like list.remove(0) both mutate the object and return a value — a pattern that can appear on tricky AP exam questions.
Common instance method categories tested on the AP exam
CategoryReturn TypeModifies State?Example
Accessor (no params)int, String, etc.Nostr.length()
Accessor (with params)int, String, etc.Nostr.substring(0, 3)
Void mutatorvoidYeslist.add("x")
Returning mutatorvariesYeslist.remove(0)

Worked Example

Consider the following code segment. We will trace through each instance method call step by step to determine the final output — exactly the process you should follow on the AP exam.

📝 CODE SEGMENT
String word = "Computer"; int len = word.length(); String sub = word.substring(3, 6); String upper = sub.toUpperCase(); int idx = word.indexOf("put"); System.out.println(upper + " " + len + " " + idx);
Tracing Instance Method Calls
1
Step 1 — Create the String ObjectThe statement String word = "Computer"; creates a String object on the heap with the character sequence {'C','o','m','p','u','t','e','r'} and stores a reference to it in the variable word. The indices run from 0 ('C') to 7 ('r').
word → "Computer"
2
Step 2 — Call word.length()The accessor method length() is called on the object referenced by word. It takes no arguments and returns an int equal to the number of characters in the String. Since "Computer" has 8 characters, the method returns 8. This value is stored in len.
len = 8
3
Step 3 — Call word.substring(3, 6)The accessor method substring(int beginIndex, int endIndex) returns a new String starting at index beginIndex (inclusive) and ending at endIndex (exclusive). For indices 3 through 5 of "Computer": index 3 = 'p', index 4 = 'u', index 5 = 't'. The returned String is "put".
sub = "put"
4
Step 4 — Call sub.toUpperCase()Now we call toUpperCase() on the String object referenced by sub (which is "put"). This is an accessor — it returns a new String with all characters converted to uppercase without modifying the original. The returned value is "PUT".
upper = "PUT"
5
Step 5 — Call word.indexOf("put")The method indexOf(String str) searches for the first occurrence of the argument within the String and returns the starting index. In "Computer", the substring "put" starts at index 3 (the 'p'). So indexOf returns 3.
idx = 3
6
Step 6 — Print the ResultThe println statement concatenates upper ("PUT"), a space, len (8), a space, and idx (3). The int values are automatically converted to Strings during concatenation.
Output: PUT 8 3

Instance Methods vs. Static Methods

One of the most common sources of confusion on the AP exam is the distinction between instance methods and static methods. Both are defined within a class, but they differ fundamentally in how they are called and what data they can access. The table below provides a side-by-side comparison that clarifies these differences.

Instance vs. Static Methods — Key Differences
FeatureInstance MethodStatic Method
Declared with static?NoYes — includes the static keyword
How it is calledobjectRef.method()ClassName.method()
Requires an object?Yes — must be called on a specific instanceNo — belongs to the class itself
Access to instance variables?Yes — via the implicit this referenceNo — cannot use this or instance fields
Common AP examplestr.length()Math.sqrt(25)
KEY TAKEAWAY
Think of a static method as a utility function in a factory's instruction manual — it does not require a specific product to operate (e.g., Math.abs(-5)). An instance method is like pressing a button on a specific product to query its unique serial number or update its firmware — the operation only makes sense in the context of one concrete object. If you see ClassName.method(), it is static; if you see variableName.method(), it is almost certainly an instance method.
⚠️ COMMON MISTAKE
Attempting to call an instance method using the class name (e.g., String.length()) will cause a compile-time error because the compiler does not know which String object's length to return. Always verify you have an object reference before calling an instance method.

Connections to Inheritance & Polymorphism

Once you are comfortable calling instance methods on objects whose compile-time type matches their runtime type, the AP curriculum introduces inheritance and polymorphism, which add a deeper layer to method invocation. When a subclass overrides an instance method, the version that executes depends on the object's actual (runtime) type, not the declared (compile-time) type of the reference variable. This is called dynamic dispatch, and it is one of the most powerful consequences of calling instance methods in an object-oriented language.

Basic vs. Polymorphic Instance Method Calls
ConceptBasic Instance Method CallPolymorphic Instance Method Call
Reference typeSame as object typeSuperclass or interface type
Which method runs?The class's own methodThe overridden version in the runtime class
Compile-time checkMethod must exist in declared typeMethod must exist in declared type (same rule)
AP exam relevanceUnits 2 & 5Unit 9 — tested in FRQs

Understanding dynamic dispatch begins with the foundational skill of calling instance methods. When you write Animal a = new Dog(); a.speak();, Java first confirms at compile time that the class Animal has a speak() method. At runtime, because the actual object is a Dog, the JVM calls Dog's overridden speak(). This seamless behavior relies entirely on the instance method calling mechanism you are learning in this lesson — the dot operator, the object reference, and the argument list remain identical regardless of polymorphism.

Practice Problems

1
Which of the following best explains why an instance method must be called on an object reference rather than using a class name?
2
Consider the following code segment: String s = "AP exam"; System.out.println(s.substring(3).length()); What is printed as a result of executing this code?
3
Consider the following code segment: String word = "banana"; int result = word.indexOf("an"); String part = word.substring(result, result + 3); System.out.println(part.toUpperCase()); What is printed as a result of executing this code?
PROBLEM 4APPLIED
A Student class has the following methods: public String getName() // returns the student's name public double getGPA() // returns the student's GPA public void setGPA(double gpa) // sets the student's GPA public boolean isHonors() // returns true if GPA >= 3.5 Write a code segment that creates a Student object with the name "Alice" and a GPA of 3.2, updates the GPA to 3.7, and then prints "Alice: Honors" if the student qualifies for honors, or "Alice: Regular" otherwise. Assume the constructor is Student(String name, double gpa).
PROBLEM 5CRITICAL THINKING
A programmer writes the following code segment expecting it to print 0, but it prints −1 instead. Identify the logical error and explain, using the concepts of instance methods and return types, why the output is wrong. Then provide a corrected version. String greeting = "Hello World"; greeting.toUpperCase(); int pos = greeting.indexOf("HELLO"); System.out.println(pos);

Lesson Summary

Calling instance methods is the primary way you interact with objects in Java. Every call follows the dot operator syntax: objectReference.methodName(arguments). The object reference identifies which object to act upon, the method name specifies the behavior, and the arguments supply the data. Methods are classified as accessors (which return information without modifying state) or mutators (which change the object's internal state). A non-void method returns a value that must be captured or used in an expression; a void method is called as a standalone statement.

Key exam skills include tracing method chaining (evaluating left to right), distinguishing instance methods from static methods (instance methods require an object; static methods use a class name), and recognizing that String methods return new String objects because Strings are immutable. Mastering instance method calls prepares you for advanced topics like polymorphism and dynamic dispatch, where the runtime type of the object determines which overridden method executes.

Varsity Tutors • AP Computer Science A • Calling Instance Methods