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:

public class Autoboxing {
public static void main(String[] args) {
Short s = Short.valueOf("10");
Short s1 = s;
System.out.println(s == s1); // Prints true once that s and s1 refer to the same object
s--; // We can use s as a primitive type
System.out.println(s); // Prints 9
System.out.println(s == s1); // Prints false, again wrapper classes are not immutable like Strings.
}
}
view raw gistfile1.java hosted with ❤ by GitHub

Comparasion of Boxing

Let's do something really weird

package br.com.ocjp.autoboxing;
public class AutoBoxing1 {
public static void main(String[] args) {
Long x = Long.valueOf(10);
Long y = Long.valueOf(10);
System.out.print("x and y are == "); // What????
System.out.println(x == y);
System.out.println("x and y are equals " + x.equals(y)); // it's not a surprise
System.out.println("Another example....");
Long x1 = Long.valueOf(130);
Long y1 = Long.valueOf(130);
System.out.print("x1 and y1 are == "); // normal behaviour
System.out.println(x1 == y1);
System.out.println("x1 and y1 are equals " + x1.equals(y1)); //normal behaviour
}
}
view raw gistfile1.java hosted with ❤ by GitHub

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: