This question already has an answer here:
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();
}
}
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.
The rule for this is in the JLS section 8.4.7:
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:
In your case, the condition expression is a constant with value
true
, and there aren't anybreak
statements (reachable or otherwise) so thewhile
statement can't complete normally.To more clarification try this
It says
unreachable
statement