Conditional operator and if-else work different?

Viewed 63

This is not an error in Java 7

return (sum>9)? superDigit(sum,1): sum; 

whereas

if(sum>9) superDigit(sum,1); 
else return sum; 

this throws a "missing return statement" error. Why?

2 Answers

You're missing return statement in your if condition. Actually, it must be:

if(sum>9) 
    return superDigit(sum,1); 
else return sum;

or you can simplify:

if(sum>9) 
    return superDigit(sum,1); 
return sum;
return (sum>9)? superDigit(sum,1): sum;

is ternary operator statement.The whole is one statement.

if(sum>9) superDigit(sum,1); else return sum; 

is if/else conditional statement.Each conditional branch must be a complete statement or a stack of statements.

Related