wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes is this condition always false? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "is this condition always false?" Watch "is this condition always false?" New topic
Author

is this condition always false?

pras
Ranch Hand

Joined: Apr 04, 2007
Posts: 188
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

Joined: Nov 03, 2006
Posts: 1358
    
  17


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

Joined: Apr 04, 2007
Posts: 188
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

Joined: Jun 22, 2007
Posts: 62
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 ]

SCJP 5 & 6, SCWCD 5, SCBCD 5
Francesco Bianchi
Ranch Hand

Joined: Jun 22, 2007
Posts: 62
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;

 
wood burning stoves
 
subject: is this condition always false?