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?
It matters because ||, being the conditional "OR" operator, won't evaluate the right expression if the left expression is true, because the result can already be determined. This is known as "short-circuit" behavior.
Section 15.24 of the JLS covers this:
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 is false.
The right hand expression is not evaluated, so the NullPointerException is avoided.
(The && conditional "AND" operator, also "short circuits" and will only evaluate the right side if the left side is true.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With