Search code examples
javawhile-loopscjp

Confusing while block


The following code block gives me a compile time error.

        while(false)
        {
          System.out.println("HI");
        }

The error says that there is an unreachable statement. BUT the following code compiles

   boolean b=false;
   while(b)
   {
        System.out.println("Hi");
    }

All i could think of was this -> In case-1 as false is a literal so the compiler finds that its unreachable and in case 2 variable b in while condition block is checked at runtime so there is no compilation error?


Solution

  • The compiler sees while(false), which will never be true, so you cannot reach the println. This throws an error.

    Meanwhile, although while(b) will never be true either, the compiler doesn't automatically know this, because b isn't automatically false, it is a boolean that happens to have the value false, it could change at some point. (It doesn't here, but it could have).

    To make this point more general, the compiler will look at the type of a variable, but not what the variable actually is. Many beginning programming classes have sections which deal with how polymorphism and type casting leads to run-time errors in some cases, and compiler errors in others. If you happen to have taken a course such as these, you can think of your question here as having a similar explanation.