Originally posted by Saha Kumar:
Hello All,
One of the mock exams states that the following code
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);
produces the following output:
false
true
true
false
Why is this? I understand that the primitive boolean true, false are stored as immutable objects.
Thanks in advance.
-Saha
b1, b2, and b4 refer to different Boolean objects. b3 refers to a boolean primitive. When you use == between object references, it tests whether the references point to the same object. If you use == between a Boolean and boolean, then the Boolean will be autounboxed to a boolean.