This "if" score in Java with three simultaneous expressions

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

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

Unfortunately, I had no idea what the answer was.

+46
java
Sep 24 '15 at 10:51
source share
1 answer

There is a simple trick here.

You cannot think about it with logical logic only. Using this, this combination ...

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

... will never return true .

However, the != Operator compares links if its operands are objects.

So, the following returns true :

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

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

+80
Sep 24 '15 at 10:54
source share



All Articles