-4

I have no idea to resolve this, k and i what type will be?

while (k<=i && i<=k && k!=i){
}
user3399567
  • 67
  • 1
  • 6
  • 1
    You're checking an impossible condition It is impossible for k to be less then or equal to i, i to be less then or equal to k and k and i to not be equal. – Abraham P Mar 09 '14 at 22:28
  • 2
    The closest I can think of is BigDecimal where `0.0` equals `0.00` is false but `0.0` compareTo `0.00` is 0. – Peter Lawrey Mar 09 '14 at 22:28
  • 1
    @AbrahamP There are rare examples where impossible maths are true in Java, but this is not one them AFAIK. – Peter Lawrey Mar 09 '14 at 22:29

2 Answers2

5
Integer i = 128;
Integer k = 128;

Due to auto-boxing, these will be two distinct objects. i <= k and k <= i will both be true as the objects will be unboxed, but i != k will also be true since == and != don't trigger unboxing.

But why are they different objects? Well, the JLS requires that integers between -128 and +127 are cached. Outside of that range you'll usually get distinct objects. If you changed this to 127 instead of 128 then i and k would both reference the same Integer object.

Actually, technically, it's legal for Java implementations to cache additional values outside that range, so your mileage may vary here. A bulletproof example would explicitly create two objects, but I like the surprise factor of the code up top.

Integer i = new Integer(128);
Integer k = new Integer(128);
Community
  • 1
  • 1
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
1

With autoboxing, == and != compares references. However <= < > and >= compare the contents unboxed values.

e.g.

Long i = -129;
Long k = -129;

The problem with using Integer as an example, is the upper limit as to when auto-boxing is cached varies. It will be at least -128 to 127 but it could be much higher. e.g. with -XX:+AggressiveOpts it might be 10000 or 20000. This means

Integer i = 128;
Integer k = 128;

May or may not be a solution depending on how the JVM is tuned.


The closest I can think of is BigDecimal where 0.0 equals 0.00 is false but 0.0 compareTo 0.00 is 0.

You would have to write the code as

while(k.compareTo(i) <= 0 && i.compareTo(k) <= 0 && !k.equals(i)) { }

and this could be an infinite loop for some values of BigDecimal.

Two examples of apparently impossible maths which work in Java are

while(x != 0 && x == -x) { }

and

while(x != x + 0) { }

There is a number of solutions for x which are in infinite loop ;)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130