Friday Java Quiz: It Can't Go Simpler Than This
Q: What will this program print? true? or false?
import java.io.*;
public class Foo {
public static void main(String[] args) {
Serializable bar = null;
System.out.println(bar instanceof Serializable);
}
}
Re: Friday Java Quiz: It Can't Go Simpler Than This
Or you can read the spec :)
JLS3 section 15.20.2, the second sentence:
"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false."
Cheers,
Rémi
JLS3 section 15.20.2, the second sentence:
"At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (§15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false."
Cheers,
Rémi
Re: Friday Java Quiz: It Can't Go Simpler Than This
Joshua Bloch in Effective Java:
all objects must be unequal to null...Many classes have equals methods that guard against this with an explicit test for null:
@Override public boolean equals(Object o) {
if (o == null)
return false;
...
}
This test is unnecessary. To test its argument for equality, the equals method must first cast its argument to an appropriate type so its accessors may be invoked or its fields accessed. Before doing the cast, the method must use the instanceof operator to check that its argument is of the correct type:
@Override public boolean equals(Object o) {
if (!(o instanceof MyType))
return false;
MyType mt = (MyType) o;
...
}
...the instanceof operator is specified to return false if its first operand is null, regardless of what type appears in the second operand [JLS, 15.20.2]. Therefore the type check will return false if null is passed in, so you don't need a separate null check.