How can “while (i == i) ;” be a non-infinite loop in a single threaded application?

前端 未结 12 1135
甜味超标
甜味超标 2020-12-04 09:41

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

12条回答
  •  感动是毒
    2020-12-04 10:29

    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 >= return false if either or both operands are NaN. The equality operator == returns false if either operand is NaN, and the inequality operator != returns true if either operand is NaN. In particular, x!=x is true if and only if x is NaN, and (x=y) will be false if x or y is NaN.

提交回复
热议问题