File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes while(false) vs. if(false) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "while(false) vs. if(false)" Watch "while(false) vs. if(false)" New topic

while(false) vs. if(false)

Adam Tkaczyk

Joined: Nov 29, 2007
Posts: 21
Hi, I don't know why
if(false) {...} compiles fine, but
while(false){...} makes compilation error.
Is this a bug?

Jari Timonen
Ranch Hand

Joined: Jan 16, 2004
Posts: 232

Code is never reached aka. executed. (Compiler error, Unreachable statement)

SCJP 5.0, SCJD URLyBird 1.3.3, OCMJEA 5 (SCEA) Factory Homes
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Hi Adam,

Java uses a simple flow analysis algorithm to find most common cases of unreachable code, and all such unreachable code blocks will be flagged as compile-time errors. That's why your "while (false) { ... }" statement produces an error.

However, Java makes a special exception for "if (false) { ... }", because programmers often use this construct during development to temporarily disable part of the program. That's why the compiler accepts this statement.

If you're interested in the nitty-gritty details, refer to the Java Language Specification's description of unreachable statements.

SCJP 5.0
Rahul Shilpakar
Ranch Hand

Joined: Aug 29, 2006
Posts: 132
If has ELSE statement in optional but while doesn't have.

while (false) doesn't make any sense because the code below it not gonna execute anyway. this is not the case with IF it has ELSE in option.

Perform for today. Adapt for tomorrow.
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Hi Rahul,

Your argument is reasonable as well. But Sun's explicitly stated intention for allowing "if (false) { ... }" was to allow "conditional compilation" of code, i.e. having code that can be enabled or disabled based on a debug flag value that's a compile-time constant. For example:

Note that because DEBUG is a compile-time constant, you'll get a compiler error if you replace any of the "if (DEBUG) { ... }" statements with "while (DEBUG) { ... }".
[ December 11, 2007: Message edited by: Kelvin Lim ]
I agree. Here's the link:
subject: while(false) vs. if(false)
jQuery in Action, 3rd edition