Monday, June 25, 2012

Autoboxing - Part 2


The most import thing to know about Autoboxing is that wrapper classes are not immutable and since Java 5 we can work with them like primitives, for instance:


Comparasion of Boxing

Let's do something really weird


What happened at line 10? Why it prints true?  The operator == compares if the instance variable points to the same object in the heap,in this case we have 2 objects, so it should print false, however in this case the comparison is primitive to primitive, it happeans because the wrapper objects are unwrapped, but watch out, it is not applicable for all wrapper classes and values, find below what classes are allowed:

- Boolean
- Byte
- Short,Integer and Long ( range -128 to 127)
- Character ( from \u0000 to \u007f (7f is 127 in decimal))

Finally make sure that a variable instance is not pointing to a null otherwise we'll get an exception (NullPointerException)

No comments: