error: unreachable statement
why is it not printing hello world?
public class Main
{
public static void main(String[] args) {
final int a=10,b=20;
while(a>b){
System.out.print("Message");
}
System.out.println("Hello World");
}
}
CodePudding user response:
The a>b
in your code is a so-called constant expression because a
and b
are final
and assigned with a literal value (same would apply if it would have been assigned with another constant expression). The Java compiler evaluates these constant expressions during compilation. Because it evaluates to false
, it decides that the while
loop will never be executed, and thus the content of the loop is an "unreachable statement", and compilation fails with an error.
It never prints "Hello World", because compilation fails, so the code is never run. Printing happens at run time, not compile time.
CodePudding user response:
Because you make a
and b
final, the java compiler sees that:
while(a > b)
will never be true. Because it knows before running the program, it won't let you keep that code. Aka you have remove the while, or remove the words final
before the variables a
and b
.