Sunday, 2 December 2012

Java puzzle ;)

    Integer a = 200, b = 200;

    System.out.println(a < b || a == b || a > b);

    System.out.println(a <= b || a > b);

I'm not the type of guy who TYPICALLY likes stuff like that. IMO code used in many java-mind-fucks is just unreal to be found in application written by someone that is not out of his mind ;) But this one posted here I find to be just lovely :)

If you have your own favorites, post them as a comment :)

Ok, but lest focus on above code sample.

Here is short answer and explanation: FALSE and TRUE. True because of both `a` and `b` are damn numbers, so it has to be truth no matter what. And false, because: `a` is NOT lower than `b`; `a` is NOT grater then `b` and `a` and `b` are not pointing to the same Intereger object. Cache size is <-128, 127> - check the Integer javadocs if needed.

But that's not all, things can start being interesting from now on. You can actually make both of those sysouts TRUE! How?

Take a look here:

from java.lang.Integer:
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the -XX:AutoBoxCacheMax=<size> option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
            if (integerCacheHighPropValue != null) {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low));
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

        private IntegerCache() {}

It's like mindfuck inside mindfuck - no1 expects this :)

Anyway, empowered with that knowledge, lets hope it's not useless, but alike to the python paradox. Knowing that little trick does NOT make you a better programmer, but there is a big chance that you ARE already a good programmer if you know about it ;-)