AP Computer Science A
One-page, printable cheatsheet
Cheatsheet visualization
Table of Contents

💻ap computer science a review

2.5 Calling a Non-Void Method

Verified for the 2025 AP Computer Science A examCitation:

In Java programming, methods are fundamental building blocks that perform specific tasks within a program. There are two primary types of methods: void methods and non-void methods. While void methods perform actions without returning any values, non-void methods complete their tasks and then return a value to whatever called them. This study guide focuses on non-void methods: what they are, how they work, and most importantly, how to properly call and use them in your programs. Understanding non-void methods is essential as they allow you to retrieve and use calculated values, access object properties, and build more complex expressions in your code.

What is a Non-Void Method?

  • A non-void method is a method that returns a value after it executes
  • The return type is specified in the method declaration (before the method name)
  • Examples of return types: int, double, boolean, String, or any object type
  • Non-void methods are used when you need to get information back after a computation

Void vs. Non-Void Methods

Void MethodsNon-Void Methods
Declared with void keywordDeclared with a specific return type
Do not return valuesMust return a value of the specified type
Called as standalone statementsUsually called as part of expressions or with assignment
Used for performing actionsUsed for computing and retrieving values
Example: System.out.println()Example: Math.sqrt()

Anatomy of a Non-Void Method

Method Signature Components

Public: an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.

public int calculateTotal(double price, int quantity) {
    double total = price * quantity;
    return (int)total;
}
  • Access modifier (public) - Controls visibility

  • Return type (int) - Specifies what type of value will be returned

  • Method name (calculateTotal) - Identifies the method

  • Parameters (double price, int quantity) - Input values the method needs

  • Return statement (return (int)total;) - Sends a value back to the caller

Calling Non-Void Methods

Basic Syntax

To call a non-void method, you need to:

  1. Reference the object (if non-static) or class (if static)
  2. Use dot notation followed by the method name
  3. Provide required arguments in parentheses
  4. Capture or use the returned value

Ways to Use the Return Value

  1. Store in a variable:

    double radius = 5.0;
    double area = Math.PI * Math.pow(radius, 2);
    
  2. Use in an expression:

    double totalCost = calculateSubtotal() + calculateTax();
    
  3. Use as a parameter in another method:

    System.out.println(student.getName());
    
  4. Use in a conditional statement:

    if (number.isPrime()) {
        System.out.println("This is a prime number!");
    }
    

Common Non-Void Methods in Java

String Class Methods

  • length() - Returns the number of characters in a string

  • substring(int beginIndex, int endIndex) - Returns a new string that is a substring

  • indexOf(String str) - Returns the index of the first occurrence of a substring

  • equals(Object obj) - Returns boolean indicating if two strings have the same value

Math Class Methods

  • Math.sqrt(double a) - Returns the square root of a value

  • Math.pow(double a, double b) - Returns a raised to the power of b

  • Math.random() - Returns a random value between 0.0 (inclusive) and 1.0 (exclusive)

  • Math.abs(int a) - Returns the absolute value of a number

Key Concepts to Remember

Proper Usage Requirements

  • The return value must be used in some way - stored in a variable, used in expression, etc.

  • The variable type must match (or be compatible with) the method's return type

  • When a non-void method is called, it temporarily gets replaced by its return value

Common Mistakes to Avoid

  • Forgetting to use the return value (treating a non-void method like a void method)
  • Mismatching data types between the return value and the receiving variable
  • Not providing required arguments when calling the method
  • Calling instance methods without an object reference

Example: Working with Non-Void Methods

Consider a Student class with various non-void methods:

public class Student {
    private String name;
    private int[] testScores;
    
    // Constructor and other methods omitted for brevity
    
    public String getName() {
        return name;
    }
    
    public double getAverageScore() {
        int sum = 0;
        for (int score : testScores) {
            sum += score;
        }
        return (double) sum / testScores.length;
    }
    
    public boolean isPassing() {
        return getAverageScore() >= 60.0;
    }
}

Here's how to work with these methods:

public class StudentTester {
    public static void main(String[] args) {
        Student student1 = new Student("Alex", new int[]{85, 92, 78});
        
        // Store return value in a variable
        String studentName = student1.getName();
        System.out.println("Student name: " + studentName);
        
        // Use return value in an expression
        System.out.println("Average score: " + student1.getAverageScore());
        
        // Use return value in a conditional
        if (student1.isPassing()) {
            System.out.println(studentName + " is passing the course!");
        } else {
            System.out.println(studentName + " needs to improve their scores.");
        }
        
        // Combining multiple non-void method calls
        double curvedAverage = student1.getAverageScore() + 5.0;
        System.out.println("Curved average: " + curvedAverage);
    }
}

Method Chaining

In many cases, you can chain multiple non-void method calls together when each method returns an object:

// Getting the first 3 characters of a student name and converting to uppercase
String nameInitials = student1.getName().substring(0, 3).toUpperCase();

// Equivalent to:
String name = student1.getName();
String initials = name.substring(0, 3);
String upperInitials = initials.toUpperCase();

Non-void methods are essential tools in Java programming that allow you to retrieve values from objects or classes. Unlike void methods which only perform actions, non-void methods return data that can be stored, manipulated, or used in other operations. When calling non-void methods, always remember to capture or use their return values - this is what makes them different from void methods. As you continue with your AP Computer Science A course, you'll find that non-void methods become increasingly important for building complex and efficient programs.

Key Terms to Review (22)

Boolean Expressions: Boolean expressions are statements that evaluate to either true or false. They are commonly used in programming to make decisions and control the flow of a program.
CalculateRectangleArea(double length, double width): The calculateRectangleArea method is used to calculate the area of a rectangle based on its length and width. It takes in the length and width as input parameters and returns the calculated area.
CalculateCircleArea(double radius): The calculateCircleArea method is used to compute the area of a circle based on its radius. It takes in the radius as input and returns the calculated area.
CalculateTriangleArea(int base, double height): This function calculates the area of a triangle using its base length and height.
Class Definition: A class definition is a blueprint or template for creating objects of a particular type. It defines the properties and behaviors that an object of that class will have.
Data Type: A data type is a classification that specifies the type of value that a variable can hold. It determines the operations that can be performed on the variable, such as arithmetic operations or string manipulation.
Eat(): The eat() method is a function that allows an object to consume food or perform actions related to consuming food.
GetIsPremium(): The method getIsPremium() is used to check if a user has a premium account or not. It returns true if the user is a premium member, and false otherwise.
GiveRaise(int raiseAmount): This term refers to a function or method that increases an employee's salary by a specified amount.
GetSpeed(): The method getSpeed() is used to retrieve the value of the speed attribute in a program. It returns the current speed of an object or entity.
IsCondition(): The isCondition() method is used in programming to check if a certain condition is true or false. It returns a boolean value, either true or false, based on the evaluation of the condition.
IsValidEmail(String email): This method checks whether a given email address is valid or not.
MethodName(parameterListOptional): A method name is an identifier that represents an action or behavior that an object can perform. It may also include optional parameters, which are values passed into the method for it to use during its execution.
PrintBookInfo(): This term refers to a method or function that displays information about a book, such as its title, author, and publication date.
Primitive Data: Primitive data refers to basic data types that are built into a programming language, such as integers, floating-point numbers, characters, and booleans. These data types are not composed of other data types.
Public: Public is an access modifier in Java that indicates unrestricted visibility for classes, methods, and variables. Public members can be accessed from any other class or package.
Reference Data: Reference data refers to complex data types that are composed of multiple primitive or reference data types. Examples include arrays, objects, and strings. Unlike primitive data types, reference variables store references (memory addresses) rather than actual values.
Return Statement: A return statement is used in functions/methods to specify what value should be sent back as output when the function is called. It terminates the execution of a function and returns control back to where it was called from.
ReverseString(String str): This method takes a string as input and returns the reversed version of that string.
Static: In programming, "static" refers to a variable or method that belongs to the class itself, rather than an instance of the class. It can be accessed without creating an object of the class.
SumNumbers(int num1, int num2, int num3): This term refers to a function or method that adds together three numbers and returns their sum.
VariableName: A variable name is a unique identifier that is used to store and refer to a value in a program. It must follow certain rules, such as starting with a letter or underscore, and cannot be a reserved keyword.