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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)