Autoboxing And Unboxing in Java 5
by, 11-08-2011 at 06:01 PM (1296 Views)
Java 5 supports automatic conversion of primitive types (int, float, double etc.) to their object equivalents (Integer, Float, Double,...) in assignments, method and constructor invocations. This conversion is know as autoboxing.
Java 5 also supports automatic unboxing, where wrapper types are automatically converted into their primitive equivalents if needed for assignments or method or constructor invocations.For example:
Before J2SE 5.0, we could not put primitive values like int, long, float, double, char etc. into collections as they are not objects. Collections can hold object references, So we were required to use wrapper classes.Java Code:int inative = 0; inative = new Integer(5); // auto-unboxing Integer intObject = 5; // autoboxing
Consider the following example: if we want to store an int a into vector vt, we have to use wrapper class. And if we want to get element stored at position 0 of vector vt, we again have to do casting.
J2SE 5.0 has made this easy. If we want to do the same in Java 5, the code will be like:Java Code:int a = 10; Vector vt = new Vector(); vt.add(new Integer(a)); int n = ((Integer)vt.elementAt(0)).intValue();
Before J2SE 5.0, Java had primtive data types with wrappers around them, So we had to convert from one type to another manuallyJava Code:int a = 10; Vector vt = new Vector (); vt.add(a); int n = vt.elementAt(0);
But now the life is easy. J2SE 1.5s autoboxing/unboxing removes the pain of manual conversion between primitives and wrappers. Ofcourse, the compiler creates code to implicitly create objects for us.Java Code:int a = 12; Integer b = Integer.valueOf(a); int c = b.intValue();
Auto-Boxing works also in comparisons (==, <, >, etc.). For instance you can compare int with Integer.Java Code:int a = 12; Integer b = a; int c = b;
Output:Java Code:int a = 10; Integer b = 10; System.out.println(a==b);
Few things to remember when using autoboxing/unboxing is that java compiler actually manages type conversions for us. So boxing and unboxing too many values can make garbage collector go wild. Hence it is not a advisable to use autoboxing and unboxing for scientific computing, or other performance-sensitive numerical code as it will affect the performance to a good extent.Using primitive types will better serve the purpose there.