Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

This 'if' evaluation in Java with three simultaneous expressions [duplicate]

Tags:

java

I had this question in my Java test where I had to assign values to a and b so this expression evaluates to true:

(a<=b && b<=a && a!=b)

Sadly, I had no idea what the answer was.

like image 242
Jhonny Avatar asked Sep 24 '15 10:09

Jhonny


1 Answers

There's a simple trick here.

You cannot think this through with boolean logic only. Using that, this combination...

  • a is less than or equal to b, and
  • b is less than or equal to a, and
  • a is not equal to b

...would never return true.

However, the != operator compares references if its operands are objects.

So, the following will return true:

Integer a = 1;
Integer b = new Integer(1);
System.out.println(a<=b && b<=a && a!=b);

What happens here is: a as an object reference is not equal to b as an object reference, although of course they hold equal integer values.

like image 179
Mena Avatar answered Oct 21 '22 04:10

Mena