Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite loop breaks method signature without compilation error [duplicate]

I am wondering why is the following code allowed in Java, without getting compilation error? In my opinion, this code breaks method signature by not returning any String. Could someone explain what I'm missing here?

public class Loop {

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

  public static void main(String[] a) {
    new Loop().withoutReturnStatement();
  }
}
like image 455
Simo Martomaa Avatar asked Aug 06 '14 07:08

Simo Martomaa


2 Answers

The final } of the method is unreachable - you only get a compilation error if it's possible to get to the end of the method without returning a value.

This is more useful for cases where the end of the method is unreachable due to an exception, e.g.

private String find(int minLength) {
    for (String string : strings) {
        if (string.length() >= minLength) {
            return string;
        }
    }
    throw new SomeExceptionIndicatingTheProblem("...");
}

The rule for this is in the JLS section 8.4.7:

If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).

Your method can't complete normally, hence there's no error. Importantly, it's not just that it can't complete normally, but the specification recognizes that it can't complete normally. From JLS 14.21:

A while statement can complete normally iff at least one of the following is true:

  • The while statement is reachable and the condition expression is not a constant expression (§15.28) with value true.
  • There is a reachable break statement that exits the while statement.

In your case, the condition expression is a constant with value true, and there aren't any break statements (reachable or otherwise) so the while statement can't complete normally.

like image 119
Jon Skeet Avatar answered Nov 13 '22 19:11

Jon Skeet


 private String withoutReturnStatement() {
    while(true) {
        // you will never come out from this loop
     } // so there will be no return value needed
    // never reach here ===> compiler not expecting a return value
  }  

To more clarification try this

private String withoutReturnStatement() {
    while(true) {}
    return ""; // unreachable
}

It says unreachable statement

like image 40
Ruchira Gayan Ranaweera Avatar answered Nov 13 '22 19:11

Ruchira Gayan Ranaweera