Reputation:
Example 1:
public class ExampleWhile {
public static void main(String args[]) {
int a = 10, b = 20;
while (a < b)
{
System.out.println("hello");
}
System.out.println("hi");
}
}
Example 2:
public class ExampleWhile2 {
public static void main(String args[]) {
while (true)
{
System.out.println("hello");
}
System.out.println("hi"); // Compile time error saying unreachable statement
}
}
Why there is a compile time error in example 2 when example 1 runs without error?
Upvotes: 4
Views: 634
Reputation: 26185
The Java Language Specification gives specific rules, in 14.21. Unreachable Statements, for the compile time error.
The rule that applies to the sample code is:
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.
The first of the two conditions is true for Example 1, but false for Example 2. The second condition is false for both examples. As far as the language specification is concerned, there is a possibility that the first loop might complete normally, allowing control to reach the following statement. There is no such possibility for the second example.
The rules achieve two benefits. There is a single set of rules for whether a sequence of characters constitutes a compilable Java program, regardless of the choice of compiler. The rules can be implemented very simply.
Upvotes: 1
Reputation: 48404
Because the compiler is "clever" enough to know that while(true)
is an infinite loop, hence System.out.println("hi");
would never be executed.
It is not clever enough to infer the same with variables, even when scoped to the method.
With compile-time constants (static final int
makes the integer a compile-time constant. Compile time constants will be available as part of the byte-code itself), it's another story:
static final int A = 0;
static final int B = 1;
public static void main(String[] args) {
while (B > A) {
}
// won't compile!
System.out.println("Foo");
}
Upvotes: 10
Reputation: 9427
The compiler does not know about the values of a and b, so it doesn't see it as an infinite loop with an unreachable statement.
With while(true), on the other hand, the compiler knows there 'll be trouble.
Upvotes: 3