How can "a <= b && b <= a && a != b" be true? [duplicate] How can "a <= b && b <= a && a != b" be true? [duplicate] java java

How can "a <= b && b <= a && a != b" be true? [duplicate]


This is not possible with primitive types. You can achieve it with boxed Integers:

Integer a = new Integer(1);Integer b = new Integer(1);

The <= and >= comparisons will use the unboxed value 1, while the != will compare the references and will succeed since they are different objects.


This works too:

Integer a = 128, b = 128;

This doesn't:

Integer a = 127, b = 127;

Auto-boxing an int is syntactic sugar for a call to Integer.valueOf(int). This function uses a cache for values less than 128. Thus, the assignment of 128 doesn't have a cache hit; it creates a new Integer instance with each auto-boxing operation, and a != b (reference comparison) is true.

The assignment of 127 has a cache hit, and the resulting Integer objects are really the same instance from the cache. So, the reference comparison a != b is false.


Another rare case for class-variables may be that another thread could change the values of a and b while the comparison is executing.