What is the difference between if(false) and while(false)

The difference is while(false) gives compilation error but if(false) does not.
See this program

public class Fun {
public static void main(String[] args){
if(false){}//Runs fine
while(false){}//Compilation error

The Java compiler won't complain about unreachable code due to an if statement with a constant expression, such as if (false). The if statement is a special case, because Java's designers wanted to allow us to use compile-time constant booleans to enable conditional compilation. Basically, if (false) {...} is allowed, but while (false) {...} is not.

1 comment: