Java – What would cause a while-loop to execute, even when false?

First of all, I’m not going to find the bug in your code for you. Debugging your own code is something you are supposed to be learning.

To answer your question:

What would cause a while-loop to execute, even when false?

Nothing would!

The loop condition is in some sense1 true. You might not think so, and / you might not understand why, but it >>is<< true.

So what should you do? Well in a situation like this where an application is behaving in a way that makes no sense (to you), the first thing to do is to use a debugger.

  1. Start the debugger.
  2. Set a breakpoint on the while statement.
  3. Start the program running.
  4. When it hits the breakpoint, use the debugger to examine the variables. In this case downPaymentPassed, boatPrice and boatIsNew.
  5. Work out what the condition should evaluate to.

I predict that you will find that one or more of the variables does not have the value that you think it should have … at that point.

One possibility that should be considered is that downPaymentPassed < boatPrice * .30 gives an unexpected answer because of rounding error. Floating point arithmetic and floating point literals (like .30) are not exact. (I’m NOT saying that that IS the problem here, but it might be … depending on what values the variables contain.)


1 – I’m be slightly cagey here. It is theoretically possible that 1) you have a hardware fault, 2) there is a compiler bug, 3) your computer keeps on getting zapped by cosmic rays. It another possible explanation (in a multithreaded application) is that the apparently inexplicable result is due to a concurrency bug; e.g. non-synchronized access to share variables. However, you should discount these possibilities here.

Leave a Comment