Hi,
The instanceof operator returns true when the first operand is not null and it can be casted to a type of the second operand without throwing a ClassCastException.
If the first operand is null and it can be casted to a type of the second operand without throwing a ClassCastException, instanceof returns false.
If the first operand cannot be casted to a type of the second operand without throwing a ClassCastException, there is a compile-time error.
Here it is an example,
class Point { int x, y; }
class Element { int atomicNumber; }
class Element2 extends Element{}
public class ClsPruebas1 {
public static void main(
String[] args) {
Point p = new Point();
Element e = new Element();
Element2 e2=new Element2();
Element2 e3=null;
System.out.println(e2 instanceof Element); //returns true
System.out.println(e3 instanceof Element); //returns false
System.out.println(e3 instanceof Point); //compiler-time error
}
}
Hope it helps,
Cristina