• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Something about auto-boxing/unboxing in SE5

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Boxing{

public static void main(String[] args){
Boolean B1 = new Boolean(true);
Boolean B2 = new Boolean(true);
boolean b = true;
System.out.println("B1 == B2 : " + (B1 == B2));
System.out.println("B1 == b : " + (B1 == b));
System.out.println("B2 == b : " + (B2 == b));

}
}
-----
The result is:
false
true
true
-
Is it puzzling?
why B1==b and B2==b, but B1!=B2?
or in other word, why B1!=B2, but B1==b and B2==b ?

Who could tell me why?
Thanks.
[ September 20, 2006: Message edited by: Ling Mike ]
 
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When comparing two objects in order for == to be true they must both reference the same object.

When comparing an object with a primitive the object is unboxed and therefore the == can return true.
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
System.out.println("B1 == B2 : " + (B1 == B2));//references are being compared ,B1 and B2 dont refer to same object.so has to be false.
System.out.println("B1 == b : " + (B1 == b));//equal to B1.booleanValue()==b
System.out.println("B2 == b : " + (B2 == b));//equal to B1.booleanValue()==b

Refer JLS 5.1.8
reply
    Bookmark Topic Watch Topic
  • New Topic