I have no idea to resolve this, k and i what type will be?
while (k<=i && i<=k && k!=i){
}
I have no idea to resolve this, k and i what type will be?
while (k<=i && i<=k && k!=i){
}
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);
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 ;)