File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes are these one and the same Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

are these one and the same

Vishal Hegde
Ranch Hand

Joined: Aug 01, 2009
Posts: 1055

is
Integer i=100; equivalent to

Integer i=new Integer(100);


http://www.lifesbizzare.blogspot.com || OCJP:81%
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

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.


Steve
Vishal Hegde
Ranch Hand

Joined: Aug 01, 2009
Posts: 1055

THEn what is Integer i=100 if its not auto boxing?
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

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

Joined: Jun 21, 2008
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

Joined: Aug 01, 2009
Posts: 1055

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
Marshal

Joined: Mar 22, 2005
Posts: 41601
    
  55
See http://faq.javaranch.com/java/JavaIntermediateFaq#integerAutoBoxing


Ping & DNS - my free Android networking tools app
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38481
    
  23
Closing because this appears to be a duplicate of this thread.
 
Don't get me started about those stupid light bulbs.
 
subject: are these one and the same