if(false) vs. while(false): unreachable code vs. dead code

The JLS section on unreachable code explains the rationale. Essentially, Java normally shouldn't use conditional compilation like C routinely does with #ifdef, but there are some situations (such as debugging, and in particular backward binary compatibility) where allowing the compiler to entirely strip out code is needed, and so the specific construct if(false) is permitted for that purpose.


You must read the Unreachable Statements. Although with while(false) the compiler will throw an error but with if(false) it wil show a warning to the user.

Although if (false) was kept in Java to simulate C/C++ preprocessor #if 0

The specification says that:

if (false) { x=3; }

does not result in a compile-time error. An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false; and then write code such as:

if (DEBUG) { x=3; } The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.