The return Statement


The return Statement

The return statement is a transfer of control statement that is used to exit a method. The return statement can return a value from a method. The type of the value that is returned must match the return type from the method declaration. A method that has a return type of void would simply use the return statement by itself. The following are all valid return statements ”

 return; return Math.PI; return 2.3; 

A method can contain any number of return statements. A method can return reference as well as primitive type variables . When the return type is an object, the return value must be an instance of the return type class or a subclass of that class. For example, the Stack class is a subclass of the Vector class. A method with a return type of Vector could return a Stack object as well as a Vector object.

Example: Using return Statements

The ReturnDemo class defines the nonNegative() method that defines two return statements. If the value of the input argument is less than zero, the first return statement returns the numeric literal value 0.0 . If the argument is greater than zero, the second return statement returns the input argument variable.

 public class ReturnDemo {   //  The nonNegative() method defines two return   //  statements.  One returns a literal value,   //  the other returns a variable   public double nonNegative(double value) {     if ( value < 0 ) {        return 0.0;     } else {        return value;     }   }   public static void main(String args[]) {     double d;     ReturnDemo demo = new ReturnDemo();     d = demo.nonNegative(-2.0);     System.out.println("value is "+d);     d = demo.nonNegative(4.3);     System.out.println("value is "+d);   } } 

Output ”

 value is 0.0 value is 4.3 

Many other examples of return statements can be found throughout this book.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net