Why is a compiler error received for the following code in Java?
public static int compileError(int n) {
if (n > 0)
return 10;
else if (n == 0)
return 0;
else if (n < 0)
return -10;
}
Since there is no "else" statement, the compiler cannot be sure that the method always returns an integer because if conditions might not cover all the statements. The compiler error can be fixed by changing the last "else if" with "else".
public static int noCompileError(int n) {
if (n > 0)
return 10;
else if (n == 0)
return 0;
else
return -10;
}