The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


The Return Statement

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

  public static void printLogarithm (double x) {
    if (x <= 0.0) {
      System.out.println ("Positive numbers only, please.");
      return;
    }

    double result = Math.log (x);
    System.out.println ("The log of x is " + result);
  }

This defines a method named printLogarithm that takes a double named x as a parameter. The first thing it does is check whether x is less than or equal to zero, in which case it prints an error message and then uses return to exit the method. The flow of execution immediately returns to the caller and the remaining lines of the method are not executed.

I used a floating-point value on the right side of the condition because there is a floating-point variable on the left.



Last Update: 2011-01-24