Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Recently I had an interview with a Software company where the following question was asked in the technical aptitude round:

Declare i in such a way that the condition is always true :

while(i != i) {
}

Is it technically possible in java to assign something of this sort??

like image 850
Bonny Mathew Avatar asked Jun 20 '17 07:06

Bonny Mathew


1 Answers

NaN is not equal to itself, so

double i = Double.NaN;

But I don't think this is a good interview question.

Quote from the Java Language Specification:

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.
like image 120
DAle Avatar answered Nov 15 '22 20:11

DAle