public class Boxing6 { public static void main(String[] args) { Boolean b1 = new Boolean(true); Boolean b2 = new Boolean(true); boolean b3 = true; Boolean b4 = true; System.out.println(b1==b2); System.out.println(b1==b3); System.out.println(b3 == b4); System.out.println(b1 == b4); } }
based on the mock exam where I found this question, the answer to this question is: false true true false
which I don't understand why?! Shouldn't the answer be: false false true false ?
Thanks in advance
Keith Lynn
Ranch Hand
Joined: Feb 07, 2005
Posts: 2341
posted
0
Notice that b3 is a primitive. When you use the == between a Wrapper and a primitive, the wrapper is unboxed.
Akhil Maharaj
Ranch Hand
Joined: Sep 29, 2007
Posts: 63
posted
0
Check this out
This code will not compile . Moral of the story I think is : Wrapper == primitive gets compiled only when both sides are compatible . After compilation is successful , During runtime - Wrapper gets unboxed .
Any comments on this theory?
[ October 22, 2007: Message edited by: Akhil Maharaj ]
[ October 22, 2007: Message edited by: Akhil Maharaj ] [ October 22, 2007: Message edited by: Akhil Maharaj ]
Mahmoud Kamal
Greenhorn
Joined: Oct 22, 2007
Posts: 5
posted
0
Originally posted by Keith Lynn: Notice that b3 is a primitive. When you use the == between a Wrapper and a primitive, the wrapper is unboxed.
Based on your reply then the following line should also return (true) since b1 will be un-boxed and b4 is already a primitive. But the question official answer says that this will return false....so why is this? System.out.println(b1 == b4);
and if the above line returned false then the line System.out.println(b1==b3);
should also return false! but that was not the case as it returned true! I am confused here about this issue, so do you have any idea about the conflict in the above 2 lines?
Thanks in advance
Thirumalai Muthu
Ranch Hand
Joined: Oct 07, 2007
Posts: 75
posted
0
b4 is not a primitive but a Boolean object because you have given it as Boolean b4 which means Java automatically wraps b4 into an Boolean object.
Since b1 and b4 are Boolean objects and also they have the same value(true).In order to save Memory two instances of Boolean objects will always be == when their primitive values are same. [ October 22, 2007: Message edited by: Thirumalai Muthu ]