Win a copy of TDD for a Shopping Website LiveProject this week in the Testing forum!
  • 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
  • Paul Clapham
  • Ron McLeod
  • Jeanne Boyarsky
  • Tim Cooke
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Frits Walraven
Bartenders:
  • Piet Souris
  • Himai Minh

Boolean doubt

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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);
}
}
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdy!

When you compare two distinct objects with == the result will be always false.

When you compare two primitives, it will be true when the value is the same or false if not.

When you compare an object of a wrapper class with a corresponding primitive, the object will be unboxed and the comparison will be as if both are primitives.

If the wrappers are of type Byte, Short, Character or Integer the story is a bit more complicated, but this is not part of the question.


Note that in the line with b4 a new object is created, just as in the first two lines, only with a different syntax (autoboxing).


Yours,
Bu.
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Burkhard Hassel:
... When you compare two distinct objects with == the result will be always false.

When you compare two primitives, it will be true when the value is the same or false if not...


The way I like to think of this is that == is a comparison of values. For primitives, this is straight forward. For objects, this means a comparison of references, so == will return true only of both operands reference the same object.

Hope that helps.
 
Why should I lose weight? They make bigger overalls. And they sure don't make overalls for tiny ads:
free, earth-friendly heat - a kickstarter for putting coin in your pocket while saving the earth
https://coderanch.com/t/751654/free-earth-friendly-heat-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic