Answer: The top answer of this thread basically answers my question: Missing return statement in a non-void method compiles.
I wonder why I do not need to return a value in this private
method?
public class Test {
private String testLoop() {
while(true) { }
}
public static void main(String[] args) {
Test test = new Test();
test.testLoop();
}
}
I feel like this should not compile. However, it compiles fine. Where is this defined to be legal?
In this context, I find it weird that changing the method to:
private String testLoop() {
while(true) {
if(false == true) {
break;
}
}
return null;
}
requires me to provide a return type even though javap tells me that the compiler produces the exact same byte code for both implementations of testLoop
.
So how and when does the Java compiler decide if a method actually needs a return value?
Unfortunately, an answer was deleted which mentioned the halting problem. I guess the Java compiler does not put effort on tracing methods like the example given above since it cannot find all possible loops in a general setting.