Skip to main content

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 improvement. 


An implementation  of flyweight design pattern . A flyweight is an object that minimises memory use by sharing as much data as possible with other similar objects.

 


so, integer  cache help auto boxing between the range [-128 to 127].
Now how auto boxing  happen?  When we do the following in java 1.5 onwards
Integer K=23;
program flow goes to following method of Integer class
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
so , above code checks if the int i lies between [-128 to 127] then the object from integer cache else it creates a new integer object using new operator.


That’s why checking equality using == operator only holds between the range -128 to 127.
one exception to above rule; if we create object using new operator and even if the integer lies between [-128 to 127] equality using == operator will not hold true when values are same.

Caching also supported by java.lang.Long and java.lang.Character
in Character class cache array hold 128 objects(The ASCII table) unlike Integer and Long.  
 





Comments

Popular posts from this blog

Greedy algorithms for Job Scheduling

In this programming problem and the next you'll code up the greedy algorithms from lecture for minimizing the weighted sum of completion times.. This file describes a set of jobs with positive and integral weights and lengths. It has the format [number_of_jobs] [job_1_weight] [job_1_length] [job_2_weight] [job_2_length] ... For example, the third line of the file is "74 59", indicating that the second job has weight 74 and length 59. You should NOT assume that edge weights or lengths are distinct. Your task in this problem is to run the greedy algorithm that schedules jobs in decreasing order of the difference (weight - length). This algorithm is not always optimal. IMPORTANT: if two jobs have equal difference (weight - length), you should schedule the job with higher weight first. Beware: if you break ties in a different way, you are likely to get the wrong answer. You should report the sum of weighted completion times of the resulting schedule --- a posi
You are given four integers 'a', 'b', 'y' and 'x', where 'x' can only be either zero or one. Your task is as follows: If 'x' is zero assign value 'a' to the variable 'y', if 'x' is one assign value 'b' to the variable 'y'. You are not allowed to use any conditional operator (including ternary operator).  Possible Solutions: 1. y = (1 - x) * a + x * b; 2.y = a ^ ((a ^ b) & (x))

Anomalies with Double check locking

Already we have a nice article about about problems with double check locking. we will see two nice quick workarounds  and its pros and cons . Double-checked locking: Clever, but broken and Double-Checked Locking is Broken . before getting into solution, classic singleton uses the following signature for get instance:      public static  Resource getResource() {     if (resource == null)       resource = new Resource();     return resource;   } so the above code will only create the new resource object if  no instance of resource is found. This mechanism is  called lazy loading more preciously need based loading we only load resources if and only if it is required. Benefit associated with this approach is performance  improvement, if resource creation is a heavy process and we do not want it to be carried when class is loading t  then this classic approach does make sense. public static synchronized Resource getResource() {     if (resource == null)       resource = n