Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# are these one and the same

Vishal Hegde
Ranch Hand
Posts: 1077
is
Integer i=100; equivalent to

Integer i=new Integer(100);

Steve Luke
Bartender
Posts: 4181
22
Vishal Hegde wrote:is
Integer i=100; equivalent to

Integer i=new Integer(100);

No, auto-boxing is like calling Integer i = Integer.valueOf(100); The difference is that there are a range of values (-128 to 128 or something like that) which are cached, so auto-boxing and the valueOf method will be quicker/more memory efficient for low int values then creating a new Integer.

Vishal Hegde
Ranch Hand
Posts: 1077
THEn what is Integer i=100 if its not auto boxing?

Steve Luke
Bartender
Posts: 4181
22
Vishal Hegde wrote:THEn what is Integer i=100 if its not auto boxing?

Integer i = 100; is auto boxing, and auto boxing has the affect of calling Integer i = Integer.valueOf(100);

Ireneusz Kordal
Ranch Hand
Posts: 423
Vishal Hegde wrote:THEn what is Integer i=100 if its not auto boxing?

For values from -128 to 128 compiler creates 'constant' integer objects in memory and refers to them.
Look at this example:

Result will be:
i == j
x != y

For values less than -128 and grather thar 128 you will get:
i != j
x != y

But except this difference the i =100 and i = new Integer(100) are equivalent.

Vishal Hegde
Ranch Hand
Posts: 1077
ohhk basically it means that when we write

Integer i1=100
Integer i2=100 // it must be within -128 to 128
and thus if the instance has same value then they are pointing to the same object and thus equal

on the other hand
Integer i1=new Integer(100);
Integer i2=new Integer(100); // in this case both referece variable i1 and i2 are different objects

Am i right??

Ulf Dittmer
Rancher
Posts: 42968
73

Campbell Ritchie
Sheriff
Posts: 50258
79
Closing because this appears to be a duplicate of this thread.