Why don't I need to provide a return value after an infinite loop?

Answer . The top answer of this topic basically answers my question: Compiling a missing return statement in a non-void compiler .


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 this should not compile. However, it compiles fine. Where is it defined as legal?

In this context, it seems strange to me that changing the method:

 private String testLoop() { while(true) { if(false == true) { break; } } return null; } 

requires me to provide a return type even if javap tells me that the compiler generates the same byte code for both testLoop implementations.

So, how and when does the Java compiler decide whether the method really requires a return value?


Unfortunately, the answer that mentioned the stop problem was deleted . I think that the Java compiler does not make any effort on trace methods, like the example above, since it cannot find all possible loops in the general setup.

+8
java
source share
5 answers
 private String testLoop() { while(true) { } //infinite loop } 

The above method never returns, since there is an infinite loop. Therefore, he does not expect a return, or he will never reach a return.

+4
source share

your while while(true) { } will never end, so the compiler does not expect a return statement. If the compiler detects that the loop will end, then it expects a return statement. You can manually test it.try with int i=1;while(i<0) this will give a compilation error, and the compiler will ask you to extract the report

+1
source share

Method

 private String testLoop() { while(true) { } } 

in fact, it does not have a return point at compile time, which means that when compiling it never comes the time at which it "searches" for a return.

This is not good practice, of course, and empty loops, especially those where the condition true should appear as an error in your IDE.

+1
source share

while (true) {} does not allow any subsequent expression that you write

 private String testLoop() { while(true) { } //any code at this point is not reachable since it wont come out of while loop. So return statement just like any java code wont be reachable. } 
0
source share

your call to the testloop method and not requiring a return value .... if you wrote it like this, then the private method would have to return something.

 String result = test.testloop(); 
-4
source share

All Articles