Back to questions
JuniorTheoryCommon
What happens when the program is compiled and run?
public class Main {
static int sign(int x) {
if (x > 0) {
return 1;
} else if (x < 0) {
return -1;
}
}
public static void main(String[] args) {
System.out.println(sign(5));
}
}It does not compile
- Expecting
1: the compiler does not look at the callsign(5); it checks that every path throughsignreturns a value, andx == 0reaches the end with none. - Expecting
0or a run-time error: a method gets no default result; a path withoutreturnstops the build withmissing return statement.
- How would you change
signso that it compiles and returns 0 for zero? - Why does a
voidmethod compile without anyreturn?