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 public static void main(String[] args) { int x = 0; if (x == x) { System.out.println("Ok"); } else { System.out.println("Not ok"); } } }
I received the following question in my lab: How can you skip the first case (i.e. make the x == x
condition false) without modifying the condition itself?
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
==
isfalse
but the result of!=
istrue
.Indeed, the test
x!=x
istrue
if and only if the value ofx
is NaN....
int x = 0; if (x == x) { System.out.println("Not ok"); } else { System.out.println("Ok"); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With