A method returns to the code that invoked it when itwhichever occurs first.
- completes all the statements in the method,
- reaches a
returnstatement, or- throws an exception (covered later),
You declare a method's return type in its method declaration. Within the body of the method, you use the
returnstatement to return the value.Any method declared
voiddoesn't return a value. It does not need to contain areturnstatement, but it may do so. In such a case, areturnstatement can be used to branch out of a control flow block and exit the method and is simply used like this:If you try to return a value from a method that is declaredreturn;void, you will get a compiler error.Any method that is not declared
voidmust contain areturnstatement with a corresponding return value, like this:The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.return returnValue;The
getArea()method in theRectangleRectangleclass that was discussed in the sections on objects returns an integer:This method returns the integer that the expression// a method for computing the area of the rectangle public int getArea() { return width * height; }width*heightevaluates to.
The
areamethod returns a primitive type. A method can also return a reference type. For example, in a program to manipulateBicycleobjects, we might have a method like this:public Bicycle seeWhosFastest(Bicycle myBike, Bicycle yourBike, Environment env) { Bicycle fastest; // code to calculate which bike is faster, given // each bike's gear and cadence and given // the environment (terrain and wind) return fastest; }Returning a Class or Interface
If this section confuses you, skip it and return to it after you have finished the lesson on interfaces and inheritance.When a method uses a class name as its return type, such as
whosFastestdoes, the class of the type of the returned object must be either a subclass of, or the exact class of, the return type. Suppose that you have a class hierarchy in whichImaginaryNumberis a subclass ofjava.lang.Number, which is in turn a subclass ofObject, as illustrated in the following figure.Now suppose that you have a method declared to return a
The class hierarchy for ImaginaryNumber
Number:Thepublic Number returnANumber() { ... }returnANumbermethod can return anImaginaryNumberbut not anObject.ImaginaryNumberis aNumberbecause it's a subclass ofNumber. However, anObjectis not necessarily aNumber it could be aStringor another type.You can override a method and define it to return a subclass of the original method, like this:
This technique, called covariant return type, means that the return type is allowed to vary in the same direction as the subclass.public ImaginaryNumber returnANumber() { ... }
Note: You also can use interface names as return types. In this case, the object returned must implement the specified interface.