Lets look at some examples.
int primitiveInt = 1000; //primitive int
Integer wrapperInt = new Integer(1000); // wrapper Integer, boxed type primitive.
Integer autoBoxedWrapperInteger = 1000; // Autoboxing, primitive is autoboxed to Integer, an
//Object is bing created
int autoUnboxedPrimitiveInt = wrapperInt; //Auto-unboxing, primitive is being assigned a value by auto-unoxing
//Comparing a primitive to boxed type, boxed type is autoboxed to primitive so the results is
// two primitives are being compared using === as opposed to 2 Objects are being ref compared
// using ==
System.out.println("primitiveInt == wrapperInt :" +
(primitiveInt == wrapperInt ? true : false));
//Two object references are being compared using ==, therefore the result is false
System.out.println("wrapperInt == autoBoxedWrapperInteger :" +
(wrapperInt == autoBoxedWrapperInteger ? true : false));
System.out.println("primitiveInt == autoBoxedWrapperInteger :" +
(primitiveInt == autoBoxedWrapperInteger ? true : false));
System.out.println("primitiveInt == autoUnboxedPrimitiveInt :" +
(primitiveInt == autoUnboxedPrimitiveInt ? true : false));
Output
primitiveInt == wrapperInt :true
wrapperInt == autoBoxedWrapperInteger :false
primitiveInt == autoBoxedWrapperInteger :true
primitiveInt == autoUnboxedPrimitiveInt :true
Here are some tips based on reading from Effective Java 2nd edition.
- Prefer primitives over boxed primitives.
- When you mix primitives and boxed primitive in single opeartion - boxed-primitive is auto-unboxed.
- When mixing primitives and wrapper types in expression watch out for "==" comparision.
- Performance hit due to autoboxing and unboxing, a new object is created when autoboxing is performed.
- Unboxing can throw NullPointerException
No comments:
Post a Comment