Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better: letting Java do autoboxing or using valueOf()

I am just wondering is there any difference in letting java autobox say an integer:

Integer myInteger = 3; // This will call Integer.valueOf()

or having your code as

Integer myInteger = Integer.valueOf(3);

Is there any micro optimization on this? I know the second one is more explicit, but it is also more unnecessary typing, is there any difference besides this?.

like image 446
Oscar Gomez Avatar asked Mar 09 '11 22:03

Oscar Gomez


People also ask

What is the major advantage of Autoboxing?

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 the purpose of Autoboxing?

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.

How does Autoboxing of Integer work in Java?

Autoboxing in Java is a process of converting a primitive data type into an object of its corresponding wrapper class. For example, converting int to Integer class, long to Long class or double to Double class, etc.


3 Answers

They are equal anyway internally, so use the first variant. Chances are good, that future compiler optimizations may make the first even faster in the future.

like image 181
Daniel Avatar answered Oct 07 '22 03:10

Daniel


I'd use the first choice. It's the same thing with less code.

Unless I expect that the program would have to run on an older version of JVM. However, in that case this would be far from being the only compatibility issue.

So, the only reason not to use autoboxing is if it's not available.

like image 27
Goran Jovic Avatar answered Oct 07 '22 02:10

Goran Jovic


That I know, there really isn't a huge difference in performance see this post here The difference isn't really a difference, but you should use valueOf, because Integer now caches Integer objects between -128 and 127.

like image 1
7dr3am7 Avatar answered Oct 07 '22 02:10

7dr3am7