Returning a Value from a Method
by , 04-26-2012 at 04:36 PM (228 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:
If it is tried to make a value returned from a method which has been declared voide then compiler error will come.Java Code:return;
Method not declared to be void shall consist of return statement along with corresponding return value, this way:
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.Java Code:return returnValue;
In Rectangle Rectangle class, the getArea() method returns an integer:
Integer is returned by this method, which the expression “width*height” evaluates to be.Java Code:// a method for computing the area of the rectangle public int getArea() { return width * height; }
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; }









Email Blog Entry
License4J 4.0
05-22-2013, 12:23 AM in Java Software