I have created an equals method. I believe I can do it in two ways but java doesn't seem to agree. Here is the first example which I know works.
public class HelloWorld {
public boolean equals(Object rhs){
if(this==rhs){
return true;
}else if( rhs==null || this.getClass() != rhs.getClass()){
return false;
}else{
HelloWorld tmp =(HelloWorld)rhs;
return true;
}
}
public static void main(String[] args){
HelloWorld c = new HelloWorld();
System.out.println(c.equals(null));
}
}
And here is the second example which doesn't work. Instead of returning false I get a nullpointerexception.
public class HelloWorld {
public boolean equals(Object rhs){
if(this==rhs){
return true;
}else if(this.getClass() != rhs.getClass() || rhs==null){
return false;
}else{
HelloWorld tmp =(HelloWorld)rhs;
return true;
}
}
public static void main(String[] args){
HelloWorld c = new HelloWorld();
System.out.println(c.equals(null));
}
}
My question then... The only difference between the two pieces of code is that in the first piece I've written
rhs ==null ||...
And in the second piece it's on the other side of the OR-operator so
...|| rhs==null
Why would the first case not give me a Nullpointer but the second case does? Why should it matter on which side of the OR operator i write the boolean statement?
The right-hand side of the ||
operator isn't executed if the left-hand side evaluates to true
, as per JLS section 15.24:
The conditional-or operator
||
operator is like|
(ยง15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand isfalse
.
So in your first case, rhs == null
evaluates to true, so rhs.getClass()
isn't executed - otherwise it would have thrown a NullPointerException
.
In your second case, you're executing rhs.getClass()
unconditionally, hence the exception.
If you use |
instead of ||
, you'll get an exception in both cases.
See more on this question at Stackoverflow