Thursday, February 12, 2009

Sad reality about Wrapper Classes in Java

Consider the snippet.



Integer firstInteger = 1000; // autoboxing
Integer secondInteger = 1000; //autoboxing

if (firstInteger != secondInteger) {
System.out.println("Different objects!");
}

if(firstInteger.equals(secondInteger)) {
System.out.println("Meaningfully equivalent!");
}

Output:



Different objects!
Meaningfully equivalent!

How about this one.



Integer firstInteger = 100; // autoboxing
Integer secondInteger = 100; //autoboxing

if (firstInteger == secondInteger) {
System.out.println("Equal objects!");
}

if(firstInteger.equals(secondInteger)) {
System.out.println("Meaningfully equivalent!");
}

And the output?



Equal objects!
Meaningfully equivalent!

And the explanation?


Two instances of the wrapper objects will always be == when their primitive values are the same.
- Boolean
- Byte
- Character from \u0000 to \u007F (0 to 127)
- Short from -128 to 127
- Integer from -128 to 127


Tsk.

No comments: