Win a copy of Clojure in Action this week in the Clojure forum!
    Bookmark Topic Watch Topic
  • New Topic

are these one and the same

 
Vishal Hegde
Ranch Hand
Posts: 1077
Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
is
Integer i=100; equivalent to

Integer i=new Integer(100);
 
Steve Luke
Bartender
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
THEn what is Integer i=100 if its not auto boxing?
 
Steve Luke
Bartender
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Pie
Posts: 42966
73
 
Campbell Ritchie
Sheriff
Pie
Posts: 47274
52
  • 0
  • Mark post as helpful
  • send pies
  • Report post to moderator
Closing because this appears to be a duplicate of this thread.
 
I agree. Here's the link: http://aspose.com/file-tools
    Bookmark Topic Watch Topic
  • New Topic