Auto-boxing and AutoUnboxing is the new feature added in Java 5 where java compiler automatically converts the primitive(basic) data types into corresponding object wrapper classes and vice versa.
Prior to Java 5,if we have to add int/long/double/.... primitives into any collection classes,we have to explicitly convert them into corresponding Number wrapper classes and add them into collection.However with the advent of Java 5,we need not have to explicitly do the same.It happens automatically as compiler generates the code which converts primitive to wrapper classes and vice versa.
Code prior to Java 5
Code as per Java 5
So in Java 5,we need not have to convert the primitive data types into Number wrapper classes.Its taken by the compiler which handle it seamlessly
Prior to Java 5 if we have to do any increment/decrement of the wrapper object.We have to get the primitive value from the wrapper number object ,increment/decrement the same and push it back to wrapper object.
Code prior to Java5
Code as per Java5
So in Java5,we need not have to convert wrapper objects into primitives for increment/decrement operations.
Overloading and auto boxing/unboxing
So how does auto boxing/unboxing affects overloading.It follows following principles.These are:-
i)First it tries to find the method matching the exact data type.
ii)In case of wrapper classes,if it does not find any method as per step -1.It tries to find the method matching the corresponding primitive data type.
iii)If it does not find any method corresponding to step-2.Then it tries to find the method matching the widen primitive data type.
If in a class we have overloaded method display taking byte/long as parameters and we invoke display method with Integer as parameter.It will invoke display method having long as parameter
Inorder to understand better lets go through some examples.
Example-1:-In this example we have overloaded methods taking Integer object and primitive int.So when we invoke this for int or Integer object ,it invokes the corresponding method
In this example we will test the rule -2.We have overloaded methods taking int and long primitive data type.Then we invoke the overloaded method for Long wrapper class.So when we invoke the overloaded method for Long data type,invokes the overloaded method which has primitive long as parameter.