A method returns to the code that invoked it when it completes all the statements in the method, reaches a return statement, or
throws an exception, whichever occurs first.
To declare a method's return type, it is included in its method declaration. Within the body of the method, the return statement is used to return the value.
Any method declared void does not return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
If a value from a method declared void is returned, a compiler error will occur.
Any method that is not declared void must contain a return statement with a corresponding return value, like this:
The data type of the return value must match the method's declared return type; for instance, one cannot return an int value from a method declared to return a bool.
The getArea() method in the Rectangle class that was discussed in the sections on objects returns an int:
class Rectangle {
private int width;
private int height;
// ...
// A method for computing the area of the rectangle
public int getArea() {
return width * height;
}
}
This method returns the integer that the expression width * height evaluates to.
The getArea() method returns a primitive type. A method can also return a reference type. For example, in a program to manipulate Bicycle objects, we may have a method like this:
class Bicycle {
// bicycle class
}
class RaceEnvironment {
// environment class
}
public class BicycleRace {
// ...
public Bicycle playBicycleRace(Bicycle bike1, Bicycle bike2, RaceEnvironment env) {
Bicycle winner;
// Code to calculate which bike is
// faster, given each bike's gear
// and cadence and given the
// environment (terrain and wind)
return winner;
}
}