Friday, April 3, 2009

Beware - It could be the Java integer pool!

Most of the java-developers are aware of the String pool* that Java provides. However, not many are aware of the Integer pool that java provides - which is what I have observed from my interviewing over the last 1.5 years of candiates carrying experiences ranging from 1-3 years.

Integer pool is maintained by the JVM for Integers ranging from -128 to +127. So, when a line of code like:

    Integer i1 = 10;

is executed, the JVM checks for the same in the pool of Integers it maintains and pulls one from the same. Execution of such statements (or assignments) can be done safely without having to bother (which most of us don't anyway) about any side-effects. However, the problem surfaces when you execute the following lines of code...

    Integer i1 = 100;
    Integer i2 = 100;
    if(i1 == i2) {

      System.out.println("Wow Integer pool exists !!");


The above code, when executed results in printing out the assertion that the Integer pool does indeed exist.
I leave upto you, to check what happens when the the values for i1, i2 are changed to 129.

And now a catch about it (for a good number of freshers out there :) ), the above code when changed to the following, results in nothing getting printed.

    Integer i1 = new Integer(100); // New Integer object is created and the pool is not queried.
    Integer i2 = new Integer(100); // ---- Same as Above ----
    if(i1 == i2) {

      System.out.println("Wow Integer pool exists !!");


When the code above is executed, since we explicitly ask for a 'new' object, JVM does not bother to save memory for us :) and instead, gives us new objects.

Hope this is useful...

No comments:

Post a Comment