Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Boxing vs static numbers

Is it valuable for using Integer i = NumberUtils.INTEGER_ONE instead of Integer i = 1? I don't know what happen behind auto boxing.

Thanks

like image 475
Loc Phan Avatar asked Aug 01 '11 09:08

Loc Phan


People also ask

What is the major advantage of auto boxing?

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

What is meant by auto boxing?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Is Autoboxing and Boxing same?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you.

What is difference between boxing and unboxing in Java?

The basic difference between Boxing and Unboxing is that Boxing is the conversion of the value type to an object type whereas, on other hands, the term Unboxing refers to the conversion of the object type to the value type. Answer: Unboxing is the conversion form the wrapper class to the primitive data type.


2 Answers

Basically it will be compiled into:

Integer i = Integer.valueOf(NumberUtils.INTEGER_ONE);

assuming INTEGER_ONE is declared as an int.

At execution time, assuming INTEGER_ONE has the value 1, that will actually return a reference to the same object each time, guaranteed by the Java Language Specification, because it's in the range -128 to 127. Values outside that range can return references to the same object, but don't have to.

like image 106
Jon Skeet Avatar answered Oct 08 '22 23:10

Jon Skeet


Many wrappers and utility classes in java have cached pools. Integer uses an internally cached static array of 'Integer' references to dish out when the valueOf() method is invoked. Strings also have a similar pool.

If however you do something like Integer i = 128, that will begin to impact performance since autoboxing will kick in for uncached integers (Not that it does not kick in for cached integers). Unlike the case where cached integers were returned, this statement creates a new object. Object creation is expensive and drags down performance.

[EDIT]

Clarified answer

like image 25
Deepak Bala Avatar answered Oct 08 '22 23:10

Deepak Bala