How can "while (i == i) ;" be a non-infinite loop in a single threaded application?
I just got a question that I can't answer.
Suppose you have this loop definition in Java:
while (i == i) ;
What is the type of i
and the value of i
if the loop is not an infinite loop and the program is using only one thread?
double i = Double.NaN;
The API for Double.equals() spells out the answer: "Double.NaN==Double.NaN has the value false". This is elaborated in the Java Language Specification under "Floating-Point Types, Formats, and Values":
NaN
is unordered, so the numerical comparison operators<
,<=
,>
, and>=
returnfalse
if either or both operands areNaN
. The equality operator==
returnsfalse
if either operand isNaN
, and the inequality operator!=
returnstrue
if either operand isNaN
. In particular,x!=x
istrue
if and only ifx
isNaN
, and(x<y) == !(x>=y)
will befalse
ifx
ory
isNaN
.
The value of i
is then Invalid. "Not a Number".
After some googling, i found out that you CAN have NaN ( Not a Number ) in Java! So, a Float Pointing number is the Data Type and the Value is NaN. See here
double i = Double.NaN;
NaN is not equal to anything, including itself.
float i = Float.NaN;
while(i == i) ;
System.out.println("Not infinite!");