Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I not need to provide a return value after an endless loop? [duplicate]

Tags:

java

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.

like image 878
Rafael Winterhalter Avatar asked Nov 13 '13 11:11

Rafael Winterhalter


Video Answer


2 Answers

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.

like image 114
Ruchira Gayan Ranaweera Avatar answered Oct 04 '22 06:10

Ruchira Gayan Ranaweera


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.

like image 27
Dropout Avatar answered Oct 04 '22 06:10

Dropout