This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
I find this to be odd. Can anybody offer an explanation?
This prints "yes no".
Since the first statement results in true, I assume that the boolean gets boxed to Boolean, then the two Booleans are compared, which makes me think that the == method just compares the value true or false. But the second one returns false and destroys that theory.
I believe that 'b' is actually pooling the TRUE object which the primitive b1 is also pointing to but without actually creating a 'new' object! Then b2 is using the 'new' to create it's own object which is a seperate reference, but a reference to a pointer to the TRUE.
I'm not a bytecode expert, but it seems that they're both using the constant TRUE: ldc #3; //String TRUE So their pointing to the same value that's been pooled, but through differing references? That's my take - wish I could be more empirical about HOW it's working. However, anytime you see 'new' it's going to fail the == comparison with another reference variable unless it was manually assigned to that variable (ie b3 = b2;// now both point to same ojbect through the same reference) [ December 09, 2007: Message edited by: nico dotti ]
In the case of b == b1, a Boolean object is being compared to a boolean primitive. This is a "boolean equality," so according to JLS 15.21.2, the Boolean object is unboxed and primitive booleans are compared. Both have a value of "true," so the comparison is true.
In the case of b == b2, two Boolean objects are being compared. Note that these are separate objects, each created using "new" (as opposed to autoboxing). This is a "reference equality," so according to JLS 15.21.3, the comparison is false because these do not refer to the same object.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
Hey Marc, b1 is declared to be a primitive boolean...so both comparisons are similar in nature.I think it should be some ambiguity involved with the object pool [ December 09, 2007: Message edited by: sugantha Jeevankumar ]
Originally posted by sugantha Jeevankumar: Hey Marc, b1 is declared to be a primitive boolean...so both comparisons are similar in nature.I think it should be some ambiguity involved with the object pool...
I'm sorry, I don't understand what you mean. One of these comparisons is a "boolean equality" and the other is a "reference equality" as described in the JLS. (Note that the second comparison does not involve the primitive b1, and neither of the wrapper instances are created with autoboxing.) So what are you saying? [ December 10, 2007: Message edited by: marc weber ]