while(i != i) { } - 是否可能有一个永远为真的赋值

while(i != i) { } - is it possible to have an assignment that is always true

最近面试了一家软件公司,在技术能力方面被问到以下问题:

以条件始终为真的方式声明 i :

while(i != i) {
}

在 java 技术上可以分配这种东西吗??

NaN 不等于自身,所以

double i = Double.NaN;

但我认为这不是一个很好的面试问题。

引自 Java 语言规范:

NaN is unordered, so:

  • The numerical comparison operators <, <=, >, and >= return false if either or both operands are NaN (§15.20.1).
  • The equality operator == returns false if either operand is NaN. In particular, (x<y) == !(x>=y) will be false if x or y is NaN.
  • The inequality operator != returns true if either operand is NaN (§15.21.1). In particular, x!=x is true if and only if x is NaN.