13

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??

DonCallisto
  • 29,419
  • 9
  • 72
  • 100
Bonny Mathew
  • 171
  • 1
  • 7
  • Why not? I think it should be possible given that you have declared the value of i earlier and are not changing it's value inside the loop. – Swastik Udupa Jun 20 '17 at 07:34
  • 4
    https://stackoverflow.com/questions/19416644/how-can-a-java-variable-be-different-from-itself – daveoncode Jun 20 '17 at 07:39
  • my gut feeling is that it may be related to lambdas in Java-8. For example in scala we can assign a function to a variable and the actual evaluation of variable happens not after assignment but at the time of evaluation. For example `def i = Math.random` will give different values for i every time `i` is evaluated. Not sure if something like that possible is Java-8 too. – Richeek Jun 20 '17 at 07:56
  • 1
    Maybe [this](https://stackoverflow.com/questions/18460416/in-which-case-could-a-a-return-true) post can make it clear for you – Ionut J. Bejan Jun 20 '17 at 08:00

1 Answers1

41

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.
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
DAle
  • 8,990
  • 2
  • 26
  • 45