Social Media

Autoboxing

Autoboxing was added in Java 1.5 as a means of converting between primitives and their object wrappers, and back again. The transformation is done by the Java compiler using the valueOf, xxxValue methods.

Examples –

[sourcecode language=”java”] Integer i = 10;

i = i + 10;
[/sourcecode]

So this is great news because you can stop using primitives? Not quite – you still incur an overhead on object creation –

[sourcecode language=”java”] Integer total = 0;
for (int i=1; i<5000; i++){
   total+=i;
}
[/sourcecode]

The compiler would generate code similar to –

[sourcecode language=”java”] Integer total = 0;
for(int i=1; i<5000; i++){
  int result = total.intValue() + i;
  total = new Integer(result);
}
[/sourcecode]

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment: