Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is this condition always false?

 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}


/**** is this always false because obj is an object instance and here its checked whether its a Boolean instance******************/

/**** if its always false why it is checked*********************/
 
Katrina Owen
Sheriff
Posts: 1367
18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The class Object is the mother of all objects. So all Booleans are also of type Object. But so is Integer. So if you pass an Integer object to the method above, it will be accepted, because it can be seen as an Object, but in the if condition an Integer will not be recognized as an instance of Boolean.

Only one "return" will be reached - either the first one (if we have an Object that is also Boolean), or the second one (all other Objects).

If we have a Boolean, the actual boolean value gets checked and returned. All other Objects will bypass the first return, and the method will reach the statement

[ July 19, 2007: Message edited by: Katrina Owen ]
 
pras
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi katrina,

Thanks for all your help

can you write a small code snippet explaining the two scenario's

ie when you pass a boolean object and others

/****** the value returned is a true(boolean) or something else***/
 
Francesco Bianchi
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by prasanna sheregar:
public boolean equals(Object obj) {
if (obj instanceof Boolean) {
return value == ((Boolean)obj).booleanValue();
}
return false;
}


Note that this can also be written in a easier-to-read way:



The secret is all about unboxing (a mechanism by which wrapping classes unveils the primitive they contain). In particular, the == operator, when applied to Boolean objects, calls implicitly the doubleValue() method.
Since this last observation you should notice that your implementation of the equals method is unsafe. If the obj references to a NULL object the == will cause a NullPointerException

[ July 19, 2007: Message edited by: Bianchi Francesco ]
[ July 19, 2007: Message edited by: Bianchi Francesco ]
 
Francesco Bianchi
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by prasanna sheregar:

can you write a small code snippet explaining the two scenario's


Add this method to your class, launch it and look the output.
ASSERT: value is a boolean variable which is initialized to TRUE;

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic