How can a Java variable be different from itself?

前端 未结 10 1835
日久生厌
日久生厌 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:52
    int x = 0;
    if (x == x) {
        System.out.println("Not ok");
    } else {
        System.out.println("Ok");
    }
    
    0 讨论(0)
  • 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.

    ...

    0 讨论(0)
  • 2020-11-29 17:01

    Using the same skip/change output approach from another answers:

    class Condition {
        public static void main(String[] args) {
            try {
                int x = 1 / 0;
                if (x == x) {
                    System.out.println("Ok");
                } else {
                    System.out.println("Not ok");
                }
            } catch (Exception e) {
                System.out.println("Not ok");
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-29 17:06

    Not sure if this is an option but changing x from local variable to a field would allow other thread to change its value between the reading left and right side in if statement.

    Here is short demo:

    class Test {
    
        static int x = 0;
    
        public static void main(String[] args) throws Exception {
    
            Thread t = new Thread(new Change());
            t.setDaemon(true);
            t.start();
    
            while (true) {
                if (x == x) {
                    System.out.println("Ok");
                } else {
                    System.out.println("Not ok");
                    break;
                }
            }
        }
    }
    
    class Change implements Runnable {
        public void run() {
            while (true)
                Test.x++;
        }
    }
    

    Output:

    ⋮
    Ok
    Ok
    Ok
    Ok
    Ok
    Ok
    Ok
    Ok
    Not ok
    
    0 讨论(0)
提交回复
热议问题