How can a Java variable be different from itself?

前端 未结 10 1869
日久生厌
日久生厌 2020-11-29 16:14

I am wondering if this question can be solved in Java (I\'m new to the language). This is the code:

class Condition {
    // you can change in the main
    p         


        
10条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 16:53

    One simple way is to use Float.NaN:

    float x = Float.NaN;  // <--
    
    if (x == x) {
        System.out.println("Ok");
    } else {
        System.out.println("Not ok");
    }
    
    Not ok
    

    You can do the same with Double.NaN.


    From JLS §15.21.1. Numerical Equality Operators == and !=:

    Floating-point equality testing is performed in accordance with the rules of the IEEE 754 standard:

    • If either operand is NaN, then the result of == is false but the result of != is true.

      Indeed, the test x!=x is true if and only if the value of x is NaN.

    ...

提交回复
热议问题