How does the equality between wrappers and primitives evaluated ?? Based on the following quote,
NOTE, certain primitives are always to be boxed into the same immutable wrapper objects. These objects are then CACHED and REUSED, with the expectation that these are commonly used objects. These special values are:
The boolean values true and false.
The byte values.
The short and int values between -128 and 127.
The char values in the range '\u0000' to '\u007F'.
I can understand some of the statements. But, I am confused with many statments, particularly 1, 6, 9.
One more doubt, will autoboxing be applied only at the time of assignments and not at the time of comparisions??
Joined: Mar 14, 2003
i think this above part is from scjp 1.5 syllyabus ?
pls acknowledge as me preparing for scjp1.4 and not seen == operator b/w wrapper object and primitive...
and what this autoboxing is all about ?...
Thanks and Regards,<br />Amit Taneja
Joined: Oct 24, 2000
Lalitha's posting says "I am confused with many statments, particularly 1, 6, 9."
Statement 1 concerns this code: //////////////////////////////////////////////////////////// Integer i1 = new Integer(2); Integer i2 = new Integer(2); System.out.println(i1 == i2); // false ..........1 ////////////////////////////////////////////////////////////
Here two distinct objects are created, so the references i1 and i2 are different.
The last 2 code chunks are nearly identical. The big difference is that in (6) we have (wrapper == primitive) and in (9) we have (primitive == wrapper). The real question is: does the primitive get boxed (so that a reference is compared to a reference)? Or does the wrapper get unboxed (so that a primitive is compared to a primitive)? And the answer is that the wrapped object gets unboxed.
So in Statement 6, (kkk1 == kkk2) is equivalent to (kkk1.intValue() == kkk2). And in Statement 9, (mm1 == mm2) is equivalent to (mm1 == mm2.intValue()).
Hope this helps.
Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".