I ran cross this puzzler from an advanced programming course at a UK university exam.
Consider the following loop, in which i is, so far, undeclared:
while (i == i + 1) {}
Find the definition of i
, that precedes this loop, such that the while loop
continues for ever.
The next question, which asked the same question for this code snippet:
while (i != i) {}
was obvious to me. Of course in this other situation it is NaN
but I am really stuck on the prior one. Does this have to do with overflow? What would cause such a loop to loop for ever in Java?
.equals()
method? Since i is undeclared, we may use any class of what we want.null
, sincenull == null
is true, andnull + 1
isnull
.0.2 + 0.1 == 0.3
changes its value depending on compiler settings, the phase of the moon, and so on.