Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Control Flow — Loops, Conditionals & Switch

What pitfalls come from comparing floating-point or wrapper values in loop conditions and switch?

Level II · JuniorControl Flow — Loops, Conditionals & Switch
Answer

Floating-point loop counters accumulate rounding error, so 'for (double d = 0; d != 1.0; d += 0.1)' may never terminate — always count with an int or compare with a tolerance. switch on a boxed Integer auto-unboxes and throws NullPointerException if the value is null, which a bare null check before the switch would have caught. These are the kinds of edge cases that pass unit tests with round numbers but fail in production data.

Common mistakes
  • Comparing doubles with == in loop conditions.
  • Using == on Integer wrappers in conditions.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Control Flow — Loops, Conditionals & Switch.

Practise free

More on Control Flow — Loops, Conditionals & Switch