Java Puzzle : Integer Initialization

Here is a simple program which instantiate Integer object using primitive int values with all possible ways, new operator, AutoBoxing, Integer.valueOf() .

   1: package com.test;
   2:  
   3: public class IntegerPuzzle {
   4:     public static void main(String[] args) {
   5:         Integer a = new Integer(100);
   6:         Integer b = new Integer(100);
   7:         Integer c = 100;
   8:         Integer d = 100;
   9:         Integer e = Integer.valueOf(100);
  10:         Integer f = 150;
  11:         Integer g = 150;
  12:         
  13:         System.out.println("a = b ? " + (a==b));
  14:         System.out.println("c = d ? " + (c==d));
  15:         System.out.println("d = e ? " + (d==e));
  16:         System.out.println("a = c ? " + (a==c));
  17:         System.out.println("f = g ? " + (f==g));
  18:     }
  19: }

What would be the output of  this program ?

Comments

  1. a = b ? false
    c = d ? true
    d = e ? true
    a = c ? false
    f = g ? false

    =================

    Confusion is (c==d) and (f==g) comparisons.
    Found out that if value is between -128 to 127, then it returns true. Else false

    Integer f = 127;
    Integer g = 127;
    f==g is true

    Integer f = 128;
    Integer g = 128;
    f==g is false

    Integer f = -128;
    Integer g = -128;
    f==g is true

    Integer f = -129;
    Integer g = -129;
    f==g is false

    Interesting, that it is working true for 1 byte range.

    ReplyDelete
  2. You are correct dude :)

    Why ?
    Actually like String class, Integer class also provides caching for better performance. By default it caches only -128 to 128 range of int values ,as these are most used int values. This cache is being used in only two cases
    1. Autoboxing
    2. Integer.valueOf().
    In case of new operator , this caching mechanism will get bypassed.
    Developer can increase the cache size by passing runtime argument.

    ReplyDelete

Post a Comment

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester