Skip to main content
Engineering LibreTexts

13.6: The Return Statement

  • Page ID
    15240
  • The return statement allows you to terminate a method before you reach the end of it. One reason to use return is if you detect an error condition:

    public static void printLogarithm(double x) {
        if (x <= 0.0) {
            System.err.println("Error: x must be positive.");
            return;
        }
        double result = Math.log(x);
        System.out.println("The log of x is " + result);
    }
    

    This example defines a method named printLogarithm that takes a double value (named x) as a parameter. It checks whether x is less than or equal to zero, in which case it displays an error message and then uses return to exit the method. The flow of execution immediately returns to where the method was invoked, and the remaining lines of the method are not executed.

    This example uses System.err, which is an OutputStream normally used for error messages and warnings. Some development environments display output to System.err with a different color or in a separate window.

    • Was this article helpful?