AP Computer Science A
Find gaps with guided practice
Guided practice grid visualization
Table of Contents

💻ap computer science a review

2.3 Calling a Void Method

Verified for the 2025 AP Computer Science A examCitation:

Methods are the building blocks of object behavior in Java, allowing objects to perform actions and respond to requests. Void methods, in particular, represent actions that an object can take without returning a value. Understanding how to call these methods is essential for interacting with objects and utilizing their functionality effectively.

Understanding Object Behavior

Methods Define Object Behavior

An object's behavior refers to what the object can do (or what can be done to it) and is defined by methods. Methods represent the actions that objects can perform or the ways they can be manipulated.

public class Dog {
    // Instance variables (attributes)
    private String name;
    private String breed;
    
    // Constructor
    public Dog(String name, String breed) {
        this.name = name;
        this.breed = breed;
    }
    
    // Methods (behaviors)
    public void bark() {
        System.out.println(name + " says: Woof!");
    }
    
    public void eat() {
        System.out.println(name + " is eating.");
    }
    
    public void sleep() {
        System.out.println(name + " is sleeping.");
    }
}

In this example, the Dog class defines three behaviors: barking, eating, and sleeping.

Procedural Abstraction

Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written. This concept is fundamental to object-oriented programming as it enables:

  1. Code Reuse: Methods can be called multiple times without rewriting the code
  2. Information Hiding: Internal implementation details can be hidden
  3. Modularity: Programs can be broken down into logical, manageable parts
// A programmer can use the bark() method without knowing its implementation
Dog myDog = new Dog("Max", "Golden Retriever");
myDog.bark();  // Output: Max says: Woof!

Method Signatures

A method signature for a method without parameters consists of the method name and an empty parameter list. The signature uniquely identifies a method.

// Method with signature: bark()
public void bark() {
    System.out.println("Woof!");
}

// Different method with signature: bark(int)
public void bark(int times) {
    for (int i = 0; i < times; i++) {
        System.out.println("Woof!");
    }
}

Method Execution Flow

A method or constructor call interrupts the sequential execution of statements, causing the program to first execute the statements in the method or constructor before continuing. Once the last statement in the method or constructor has executed or a return statement is executed, flow of control is returned to the point immediately following where the method or constructor was called.

public class MethodFlowExample {
    public static void main(String[] args) {
        System.out.println("Step 1: Before method call");
        
        // Method call interrupts sequential execution
        printMessage();
        
        // Execution continues here after method completes
        System.out.println("Step 3: After method call");
    }
    
    public static void printMessage() {
        System.out.println("Step 2: Inside method");
    }
}

// Output:
// Step 1: Before method call
// Step 2: Inside method
// Step 3: After method call

Calling Non-Static Void Methods

Through Objects

Non-static methods are called through objects of the class. These methods operate on the specific object's data and represent behaviors of that particular instance.

// Create an object
Calculator calc = new Calculator();

// Call non-static methods on the object
calc.clear();
calc.displayValue();

Using the Dot Operator

The dot operator (.) is used along with the object name to call non-static methods.

Student student = new Student("Alice", 11);

// Using dot operator to call methods
student.introduce();
student.submitAssignment();
student.takeExam();

Void Methods

Void methods do not have return values and are therefore not called as part of an expression. They perform an action but don't produce a result that can be used in calculations or assignments.

// Void method call - valid

printer.printDocument();

// Void method cannot be part of an expression - invalid

int x = printer.printDocument();  // Error: void cannot be converted to int

// Also invalid
if (printer.printDocument()) { }  // Error: incompatible types

Handling null References

Using a null reference to call a method or access an instance variable causes a NullPointerException to be thrown. This is one of the most common exceptions in Java.

// Potential NullPointerException
Student student = null;
student.introduce();  // Throws NullPointerException

// Proper way to handle this
if (student != null) {
    student.introduce();  // Safe to call
} else {
    System.out.println("Student is null");
}

Common Void Method Examples

From Java's Standard Library

ArrayList<String> names = new ArrayList<>();
names.add("Alice");  // void method to add element
names.clear();       // void method to remove all elements
names.remove(0);     // void method to remove element at index

Scanner input = new Scanner(System.in);
input.close();       // void method to close the scanner

System.out.println("Hello");  // void method to print

Custom Void Methods

public class Account {
    private double balance;
    
    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: $" + amount);
        }
    }
    
    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: $" + amount);
        } else {
            System.out.println("Insufficient funds");
        }
    }
    
    public void printStatement() {
        System.out.println("Current balance: $" + balance);
    }
}

// Using these void methods
Account myAccount = new Account();
myAccount.deposit(1000);
myAccount.withdraw(250);
myAccount.printStatement();

Remember that void methods are used to perform actions or cause side effects rather than compute values. They are essential for implementing object behaviors and manipulating object state. When calling void methods, always ensure that the object reference is not null to avoid NullPointerException errors.

Key Terms to Review (2)

Method: A method is a named sequence of instructions that can be called or invoked to perform a specific task or action. Methods are used for code reusability, organization, and abstraction.
Non-Static Methods: Non-static methods are functions or procedures that belong to an object and can only be accessed through an instance of the class. They can modify the state of an object and are not associated with a specific class.