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.
private String testLoop() {
while(true) { } //infinite loop
}
Above method never return since there is infinite loop there. So it is not expecting return Or it will never reach return.
The method
private String testLoop() {
while(true) { }
}
doesn't really have a return point during the compilation, which means that when it's compiled there never comes a time in which it "looks for" a return..
This isn't a good practice of course and empty cycles especially those with true
condition should pop up as an error in your IDE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With