public void testNullString ()
{
String realString = "qljf";
String nullString = null ;
testI(realString, "error 1");
testI(null , "error 2");
testI(nullString, "error 3");
}
private static void testI(final String testee, final String msg) {
if ( !(testee instanceof String)) {
System.out.println(testee + " is not an instaceof String. " + msg);
}
}
will produce :
> null is not an instaceof String. error 2
> null is not an instaceof String. error 3
Advantage:
When overwriting equals(), once you have tested for instanceof, you don't have to test for null ;
class Person (){
public boolean equals(Object o) {
if (!(o instanceof Person)) return false ;
Person obj = (Person)o ; // obj cannot be null
return obj.__fName.equals (this.__fName) ;
}
private String __fName ;
}