Skip to main content

Posts

Showing posts from September, 2014

Integer comparison using == gets tricky between -128 to 127.

Integer i=45;                                                                                                                                   Integer k=45;         System.out.println("i.hashcode= "+i.hashCode());         System.out.println("k.hashcode= "+k.hashCode());         System.out.println(i==k);         System.out.println(i.equals(k)); Out Put: i.hashcode= 45 k.hashcode= 45 true true Great, it seems work fine! now change the value of i=k=201.         Integer i=201;         Integer k=201;         System.out.println("i.hashcode= "+i.hashCode());         System.out.println("k.hashcode= "+k.hashCode());         System.out.println(i==k);         System.out.println(i.equals(k)); OutPut: i.hashcode= 201 k.hashcode= 201 false // System.out.println(i==k);   true  The reason behind this is the IntegerCache, a private static inner class in Integer class. This was feature was introduced in java 1.5 for performance improvemen