View RSS Feed

Java Object

Returning a Value from a Method

Rate this Entry
by , 04-26-2012 at 05:36 PM (451 Views)
To the code, a method is returned which invokes it, when:

  • In method, all statements are completed.
  • reaches to the a return statement or
  • an exception is thrown (covered later)

Which ever would come first?

Return type of the method is declared in the method declaration. Within method’s body, return statement is used so that to return value.

Method which has been declared void will not return value. Return statement is not need to be present in it, however it might do so. In that case the return statement could be utilized for branching out the control flow block, & exit method. It is used this way:

Java Code:
If it is tried to make a value returned from a method which has been declared voide then compiler error will come.

Method not declared to be void shall consist of return statement along with corresponding return value, this way:

Java Code:
return returnValue;
Return value’s data type shall match with the declared return type of method; one might not make an integer value to be returned, from method that has been declared for Boolean return.

In Rectangle Rectangle class, the getArea() method returns an integer:

Java Code:
    // a method for computing the area of the rectangle
    public int getArea() {
        return width * height;
Integer is returned by this method, which the expression “width*height” evaluates to be.
A primitive type is returned by the the getArea method. Reference type could also be returned by a method. For instance, the way Bicycle objects are manipulated in a program, this method might have been used:

Java Code:
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;

Submit "Returning a Value from a Method" to Facebook Submit "Returning a Value from a Method" to Digg Submit "Returning a Value from a Method" to Submit "Returning a Value from a Method" to StumbleUpon Submit "Returning a Value from a Method" to Google