Back to Using Objects

Lesson PreviewLesson 6 of 10 in this unit

2.5 Calling a Non-void Method

Part of Using Objects in AP® Computer Science A. Read the opening section, then create a free account for the full interactive lesson, practice, and progress tracking.

Calling a Non-void Method

In Java, a return statement sends a value from a method back to the place it was called. This value can be used later in your program. A method's return type specifies the type of value the method will return. For example, if a method returns an integer, its return type is int. If it doesn't return anything, its return type is void. That’s why we used the void keyword to make methods before–they didn’t return any value!

java
public class Main {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();
        int result = calculator.square(5); // Call a non-void method
        // Notice how we can treat the non-void method as a normal expression
        System.out.println("The square of 5 is " + result);
    }
}

Output

The square of 5 is 25
java
public class Calculator {
    // Non-void method with return type 'int'
    public int square(int number) {
        return number * number; // Returns the result
    }
}

Continue the full lesson in Stellar

Create a free account to unlock the remaining sections, checkpoints, course practice, and progress tracking for AP® Computer Science A.