Hi
we want to know about what is Autoboxing with an example.?
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Apr 15, 2012, 10:57 AM
Autoboxing, introduced in Java 5, is the automatic conversion the Java compiler makes between the primitive (basic) types and their corresponding object wrapper classes (eg, int and Integer, double and Double, etc). The underlying code that is generated is the same, but autoboxing provides a sugar coating that avoids the tedious and hard-to-read casting typically required by Java Collections, which can not be used with primitive types. . In short auto boxing is a capability to convert or cast between object wrapper and it's primitive type.
Previously when placing a primitive data into one of the Java Collection Framework we have to wrap it to an object because the collection cannot work with primitive data. Also when calling a method that requires an instance of object than an int or long, than we have to convert it too.
But now, starting from version 1.5 we were offered a new feature in the Java Language, which automate this process, this is call the Autoboxing. When we place an int value into a collection it will be converted into an Integer object behind the scene, on the other we can read the Integer value as an int type. In most way this simplify the way we code, no need to do an explisit object casting.
Here an example how it will look like using the Autoboxing feature:
view source
print?
01.public static void main(String[] args)
{
Map
// Here we put an int into the Map, and it accepted
// as it will be autoboxed or converted into the wrapper
// of this type, in this case the Integer object.
map.put("Age", 25);
// Here we can just get the value from the map, no need
// to cast it from Integer to int.
int age = map.get("Age");
// Here we simply do the math on the primitive type
// and got the result as an Integer.
Integer newAge = age + 10;
}
Refer
http://www.kodejava.org/examples/50.html
http://www.leepoint.net/notes-java/data/basic_types/autoboxing.html
Thanks
VulpesPosted Apr 15, 2012, 8:02 AM
http://docs.oracle.com/javase/1.5.0/docs/guide/language/autoboxing.html