Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Advanced
Jul 13, 2009

Understanding Java's Integer Pool Can Avoid Problems

The next time you come across a situation where two Integers defined with equal values fail an equivalency (==) test, remember this tip. Suppose you have two integers defined as follows:

Integer i1 = 128
Integer i2 = 128

If you then execute the test (i1 == i2), the returned result is false. The reason is that the JVM maintains a pool of Integer values (similar to the one it maintains for Strings). But the pool contains only integers from -128 to 127. Creating any Integer in that range results in Java assigning those Integers from the pool, so the equivalency test works. However, for values greater than 127 and less than -128), the pool does not come into play, so the two assignments create different objects, which then fail the equivalency test and return false.

In contast, consider the following assignments:

Integer i1 = new Integer(1); // Any number in the Integer pool range
Integer i2 = new Integer(1); // Any number in the Integer pool range

Because these assignments are made using the 'new' keyword, they are new instances created, and not picked up from the pool. Hence, testing (i1== i2) on the preceding assignments returns false.

Here's some code that illustrates the Integer pool:

public class IntegerPoolTest {
    public static void main(String args[]){
        Integer i1 = 100;
        Integer i2 = 100;
        // Comparison of integers from the pool - returns true.
        compareInts(i1, i2); 
        
        Integer i3 = 130;
        Integer i4 = 130;
        // Same comparison, but from outside the pool 
        // (not in the range -128 to 127)
        // resulting in false.
        compareInts(i3, i4); 

        Integer i5 = new Integer(100);
        Integer i6 = new Integer(100);
        // Comparison of Integers created using the 'new' keyword 
        // results in new instances and '==' comparison leads to false.
        compareInts(i5, i6); 

    }

    private static void compareInts(Integer i1, Integer i2){
        System.out.println("Comparing Integers " + 
           i1 + "," + i2 + " results in: " + (i1 == i2) );
    }
}
Shreyas Pai
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap