Java Reference
In-Depth Information
Because this is a value-returning method of type int , it must return a value of type int .
Supposethevalueof x is 10 . Then, the expression, x > 5 ,inLine1,evaluatesto true .Sothe
return statement in Line 2 returns the value 20 . Now suppose that x is 3 . The expression,
x > 5 , in Line 1, now evaluates to false .The if statement therefore fails and the return
statement in Line 2 does not execute. However, the body of the method has no more
statements to be executed. It thus follows that if the value of x is less than or equal to 5 ,the
method does not contain any valid return statements to return the value of x . In this case, in
fact, the compiler generates an error message such as missing return statement .
The correct definition of the method secret is:
public static int secret( int x)
{
if (x > 5)
//Line 1
return 2 * x;
//Line 2
return x;
//Line 3
}
Here, if the value of x is less than or equal to 5, the return statement in Line 3
executes, which returns the value of x . On the other hand, if the value of x is,
say, 10 , the return statement in Line 2 executes, which returns the value 20 and
also terminates the method.
( return statement: A precaution) If the compiler can determine that during
execution certain statements in a program can never be reached, then it will generate
syntax errors. For example, consider the following methods:
public static int funcReturnStatementError( int z)
{
return z;
System.out.println(z);
}
The first statement in the method funcReturnStatementError is the return
statement. Therefore, if this method executes, then the output statement,
System.out.println(z); , will never be executed. In this case, when the compiler
compiles this method, it will generate two syntax errors, one specifying that the statement
System.out.println(z); is unreachable, and the second specifying that there is a
missing return statement after the output statement. Even if you include a return
statement after the output statement, the compiler will still generate the error that the
statement System.out.println(z); is unreachable. Therefore, you should be
careful when writing the definition of a method. Additional methods illustrating such errors
can be found with the Additional Student Files at www.cengagebrain.com. The name of the
program is TestReturnStatement.java .
 
Search WWH ::




Custom Search