Today, while solving puzzles from Java Puzzler book I myself created a new Java Puzzle. So, in this blog I am writing about that puzzle.
Puzzle
Will the code given below results in an infinite loop.
public class MyJavaPuzzle { public static void main(String[] args) { Double i = Double.NaN; while(i != i){ System.out.println("Infinite Loop"); } } }
Solve this puzzle and have fun. Happy Puzzling!!!
Post your answer and explanation in comments.
I think it won’t
When i is defined as “Double i”, you are comparing object references hence the loop doesn’t execute. When you define i as “double i” you have a primitive type that is taken care of by the runtime and hence the loop executes.
Did I answer that correctly?
Good question. Perhaps something with autoboxing double as a Double, though it must be something Java version, arch or OS specific, as running it on Java 6 64bit on OSX, it does not result in an infinite loop.
NaN in floating point can’t equal NaN, similar to infinity in conventiinal math. So ideally it wouldnt match. However its been boxed so its now a reference check and will not loop.
Its not new its known Gotcha in Java.
its about Incomparable NaN..
When you divide by zero with double, take the square root of a negative number, overflow the maximum representable value etc. the result is a magic number called Double.NaN, Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY.
ideally you should be using
while ( Double.isNaN( d ) )
The theory is making NaN not equal to itself allows a quick and dirty way to test for a calculation going haywire.
Well, if you change
“Double i” to primitive type “double i” it will start working and enter the infinite loop
Long ago read at
http://mindprod.com/jgloss/gotchas.html
Hope this helps
Cheers:)
Its not new its known Gotcha in Java.its about Incomparable NaN..When you divide by zero with double, take the square root of a negative number, overflow the maximum representable value etc. the result is a magic number called Double.NaN, Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY.ideally you should be usingwhile ( Double.isNaN( d ) )The theory is making NaN not equal to itself allows a quick and dirty way to test for a calculation going haywire.Well, if you change“Double i” to primitive type “double i” it will start working and enter the infinite loop
+1
I don’t know if I’d call it a new puzzle.
I remember there’s already puzzle in the book about comparing references instead of values.
It is an new java puzzler. I have confirmed it with Joshua Bloch http://twitter.com/joshbloch/status/14787228197
It’s so simple!
Just test this,you will konw why!
Code:
Double i = Double.NaN;
int v =1;
while(i.equals(i)){
System.out.println(“Infinite Loop”);
if(++v == 5){
break;
}
}
Here nothing is special while (i!=i) will always fail…..