0

Is there any difference between declaring the Integer below two ways

Integer Age = 25;
Integer Age = new Integer(25); 
Matt
  • 14,906
  • 27
  • 99
  • 149
Java Beginner
  • 1,635
  • 11
  • 29
  • 51

4 Answers4

8

The first integer is sourced from the Integer pool and the == check would return true

        Integer age = 25;
        Integer a = 25;
        System.out.println(a == age);

The 2nd one creates new objects every time and the == check would return false.

        Integer age = new Integer(25);
        Integer a = new Integer(25);
        System.out.println(a == age);

I have to add that only the integers through -128 -> 127 are cached by default, so the following snippet will return false too. You can tweak this by setting the property java.lang.Integer.IntegerCache.high to a value higher than 127 and it would return true.

        Integer age = 129;
        Integer a = 129;
        System.out.println(a == age);
Deepak Bala
  • 11,095
  • 2
  • 38
  • 49
1

The first one uses autoboxing whilst the second one will create a new object every time. Its best if you can use Integer.valueOf() which will fetch from a local cache mainatained within the Integer class if it is already available within the cache.

dinukadev
  • 2,279
  • 17
  • 22
0

Yes!

Do NEVER use this line because it creates a duplicate object:

Integer Age = new Integer(25); 

It is the same like using something like this:

String age = new String("old");
sk2212
  • 1,688
  • 4
  • 23
  • 43
0

both are different we know that age is the reference variable and is stored in the stack 25 in the first line will be stored in the stack ,we can say that 25 is the address of the object in the heap u created in the second line and the heap value at the address location 25 is integer 25