Java Method Return Values

Methods in Java can return values after completing their execution. The return type is specified in the method declaration, and the return statement is used to return a value.

1. Defining Return Type

The return type is specified before the method name in the declaration. It can be any data type or void if no value is returned.

public int multiply(int a, int b) {
    return a * b;
}

2. Using the Return Statement

The return statement exits the method and optionally returns a value.

public boolean isEven(int number) {
    if (number % 2 == 0) {
        return true;
    } else {
        return false;
    }
}

3. Void Methods

If a method does not return any value, use the void keyword as the return type. Such methods can still use the return statement to exit the method early without returning a value.

public void displayMessage(String message) {
    if (message == null) {
        return; // Exits the method
    }
    System.out.println(message);
}

Key Takeaways

  • Methods can return values using the return statement.
  • The return type must match the type of value returned.
  • void methods do not return any value.
  • Returning values allows methods to provide results to the caller.