AP Computer Science A • Using Objects and Methods

Calling Instance Methods

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

AP Computer Science A illustration with code, binary digits, and programming braces
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

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.

SECTION 2

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.

SECTION 3

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.

Calling CodeString s = "hello";int len = s.length();① Object ref: s② Dot operator: .③ Method name: length④ Parentheses: ()⑤ Return captured: int lenString Object (s)Instance Variable:value = {'h','e','l','l','o'}Instance Method:public int length() {return value.length;}CALLRETURN 5Method Call Rules• Must use an object reference• Arguments must match params• Return type must be compatible• void methods: no assignment• NullPointerException if null ref
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.

SECTION 4

How Instance Method Calls Work

The Syntax Blueprint

GENERAL FORM — NON-VOID METHOD

ReturnTypevariable=objectRef.methodName(arg1,arg2,…,argn);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(arg1,arg2,…,argn);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.

SECTION 5

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.

Instance Method ClassificationInstance MethodsAccessor (Getter)Returns info, no state changeMutator (Setter)Modifies internal stateNo Parametersstr.length()list.size()With Parametersstr.indexOf("a")str.substring(0,3)Void Mutatorlist.add("x")list.set(0, "y")Return + Mutatelist.remove(0)returns old elementQuick Decision GuideDoes the method return a value? → Yes: use in expression / assign to variableIs return type void? → Yes: call as standalone statement, never assign
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.
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)

Common instance method categories tested on the AP exam

SECTION 6

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. 1

    Step 1 — Create the String Object

    The 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. 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. 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. 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. 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. 6

    Step 6 — Print the Result

    The 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

SECTION 7

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.

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)

Instance vs. Static Methods — Key Differences

✦

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.

SECTION 8

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.

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

Basic vs. Polymorphic Instance Method Calls

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.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Which of the following best explains why an instance method must be called on an object reference rather than using a class name?
  • A. Instance methods are always declared private, so they can only be accessed through an object.
  • B. Instance methods need access to the specific object's instance variables, which only exist after an object is constructed.
  • C. Instance methods can only return void, so they must be called as standalone statements.
  • D. Instance methods are compiled separately from the class and require an object to link them at runtime.
Show answer (B)
B is correct. Instance methods operate on the state (instance variables) of a particular object. Those instance variables are allocated only when an object is constructed with new, so the method needs an object reference to know which set of instance variables to read or modify. A is incorrect because instance methods can have any access modifier (public, protected, package-private, or private). C is incorrect because instance methods can return any type, not just void. D is incorrect because instance methods are compiled as part of the class; it is not a linking issue.

Question 2: BASIC CALCULATION

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?
  • A. 3
  • B. 4
  • C. 5
  • D. 7
Show answer (B)
B is correct. First, s.substring(3) is evaluated. The string "AP exam" has indices 0='A', 1='P', 2=' ', 3='e', 4='x', 5='a', 6='m'. Calling substring(3) returns "exam" (from index 3 to the end). Then .length() is called on "exam", which returns 4. A (3) incorrectly counts from index 3 without including it. C (5) may result from including the space. D (7) is the length of the original string, ignoring the substring call.

Question 3: INTERMEDIATE

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?
  • A. ANA
  • B. BAN
  • C. NAN
  • D. AN
Show answer (A)
A is correct. The string "banana" has indices: 0='b', 1='a', 2='n', 3='a', 4='n', 5='a'. Calling word.indexOf("an") finds the first occurrence of "an" starting at index 1, so result = 1. Then word.substring(1, 4) extracts characters at indices 1, 2, 3 → "ana". Finally, toUpperCase() converts this to "ANA". B is incorrect because "BAN" would require starting at index 0, but indexOf("an") returns 1, not 0. C is incorrect because "NAN" would require indexOf returning 2 (the index of 'n'), but "an" is first found at index 1. D is incorrect because "AN" only has two characters, but the substring extracts 3 characters (from result to result + 3), producing a three-character string.

Question 4: APPLIED

4 pts
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).
Show answer
Rubric (4 points): Point 1 — Object Creation: Correctly declares a Student variable and constructs the object using new Student("Alice", 3.2). The variable type must be Student and arguments must match the constructor signature. Point 2 — Mutator Call: Correctly calls setGPA(3.7) on the Student object using dot notation. The method is void, so it must be a standalone statement (not assigned to a variable). Point 3 — Accessor Calls in Conditional: Correctly uses isHonors() as the boolean condition in an if statement, and uses getName() to retrieve the name for the output string. Point 4 — Correct Output: Prints "Alice: Honors" when isHonors() returns true and "Alice: Regular" when it returns false. Uses proper string concatenation with the return value of getName(). Sample Solution: Student stu = new Student("Alice", 3.2); stu.setGPA(3.7); if (stu.isHonors()) { System.out.println(stu.getName() + ": Honors"); } else { System.out.println(stu.getName() + ": Regular"); } The output is "Alice: Honors" because after the GPA is updated to 3.7, isHonors() returns true since 3.7 ≥ 3.5.

Question 5: CRITICAL THINKING

3 pts
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);
Show answer
Rubric (3 points): Point 1 — Identify the Logical Error: The code compiles and runs, but produces an incorrect result. The call greeting.toUpperCase() returns a new String with uppercase characters, but the return value is discarded because it is not assigned to a variable. String objects in Java are immutable — toUpperCase() does not modify the original String; it returns a new one. Point 2 — Explain the Consequence: Because greeting still refers to "Hello World" (not "HELLO WORLD"), the call greeting.indexOf("HELLO") returns −1 (not found, since indexOf is case-sensitive), and −1 is printed instead of the expected 0. Point 3 — Provide Corrected Code: The return value of toUpperCase() must be captured: String greeting = "Hello World"; greeting = greeting.toUpperCase(); int pos = greeting.indexOf("HELLO"); System.out.println(pos); Now greeting is reassigned to "HELLO WORLD", indexOf("HELLO") returns 0, and 0 is printed.

SUMMARY

Lesson Summary

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