Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Java variable be different from itself?

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?

like image 299
Husam Avatar asked Oct 17 '13 01:10

Husam


People also ask

Can a Java program have two different variables with the same name?

"Of course you cannot have int x and long x fields in the same class, just as you cannot have two methods with the same name and parameter list.". A better analogy is that you cannot have a method with the same name and a different type in the same class.

Can Java variables change?

Remember that a variable holds a value and that value can change or vary. If you use a variable to keep score you would probably increment it (add one to the current value).

Can a variable name be a variable Java?

The rules for Java variable naming are fairly lax. The first letter of a variable must be either a letter, dollar sign or an underscore. After that, any combination of valid Unicode characters or digits is allowed.


1 Answers

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.

...

like image 98
arshajii Avatar answered Oct 02 '22 16:10

arshajii