简体   繁体   中英

Nested return statements in Java

Taken from enthuware.com

Which of the following implementations of a max() method will correctly return the largest value?

One of the options and explanation of why it is incorrect:- My question is why is this wrong ? Is there a rule to follow ?

int max(int x, int y){ 
  return(
    if(x > y){ 
      return x; 
    } else { 
      return y; 
    }
   );
} 

It would work if the first return and the corresponding brackets is removed.

My question is why is this wrong ? Is there a rule to follow ?

Yes, the rule is called "Language grammar and syntax."


As you found out by yourself, only the following piece of code has correct syntax.

int max(int x, int y){ 
    if(x > y){
        return x;
    } else {
        return y;
    }
}

Or better yet,

int max(int x, int y){ 
    return x > y? x: y;
}

"Nested returns" does not make sense. Once the java interpreter encounters "return" statement, it simply looks for the value to return out of the function and instantly sort of quits the functions. (Exceptions are there of course, like finally block.)

When you have a method with an X return type, each return statement must be followed by an expression that can be evaluated as X. This is not the case in your code, since the if statement has no value.

The closest thing to what you are trying to do is the ternary operator :

int max(int x, int y)
{
    return (x > y)?x:y;
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM