aspose file tools*
The moose likes Beginning Java and the fly likes Loops and if statements Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Loops and if statements" Watch "Loops and if statements" New topic
Author

Loops and if statements

Fitz Herbert
Greenhorn

Joined: Mar 22, 2003
Posts: 21
When the condition statement of a loop/if statement has a definate condition of false and so the loop/if statements body is never used, will this generate compliation errors, due to duff code?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Unlike C/C++ Java has no preprocessor to handle macros like #ifdef and #ifndef. So you cannot really do any sophisticated conditional compilation.
But the Java compiler does let you write:

Provided that the "// statements" are well formed compilable Java code, these two if statements will be treated like conditional compiled code, and in the case of the false variation will not generate any bytecode.
However if you try to use a while loop you will get unreachable code errors.
[ May 07, 2003: Message edited by: Barry Gaunt ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
Yes. Try compiling this:

Trying to compile this will result in an "unreachable code" error. However, if you change it to this:

You won't get an error. The compiler isn't very thorough when it comes to checking conditions to see if they'll be executed. If it appears that the conditional test could pass, the compiler lets it go.
You can find a lot more information in the JLS, §14.20 Unreachable Statements.
I hope that helps,
Corey


SCJP Tipline, etc.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Loops and if statements
 
Similar Threads
say what?
Break/Incrementation question
if loop inside for loop problem
while() question