Professional Documents
Culture Documents
is a String
However, applying instanceof on a null reference variable returns false. For example, the following
returns false.
public class MainClass {
public static void main(String[] a) {
String s = null;
if (s instanceof java.lang.String) {
System.out.println("true");
} else {
System.out.println("false");
}
}
}
false
Since a subclass 'is a' type of its superclass, the following if statement, where Child is a subclass of
returns true.
class Parent {
public Parent() {
}
}
class Child extends Parent {
public Child() {
super();
}
}
public class MainClass {
public static void main(String[] a) {
Child child = new Child();
if (child instanceof Parent) {
System.out.println("true");
}
}
}
is instance of A");
is instance of B");
is instance of C");
can be cast to A");
if (a instanceof C)
System.out.println("a can be cast to C");
System.out.println();
A ob;
ob = d; // A reference to d
System.out.println("ob now refers to d");
if (ob instanceof D)
System.out.println("ob is instance of D");
System.out.println();
ob = c; // A reference to c
System.out.println("ob now refers to c");
if (ob instanceof D)
System.out.println("ob can be cast to D");
else
System.out.println("ob cannot be cast to D");
if (ob instanceof A)
System.out.println("ob can be cast to A");
System.out.println();
// all objects can be cast to Object
if (a instanceof Object)
System.out.println("a may be cast to
if (b instanceof Object)
System.out.println("b may be cast to
if (c instanceof Object)
System.out.println("c may be cast to
if (d instanceof Object)
System.out.println("d may be cast to
Object");
Object");
Object");
Object");
}
}
Keywords are
basically reserved words which have specific meaning relevant to a compiler. It takes an object
whether an object is of an specified type or not and returns the value accordingly.
reference as its first reference and a class or interface as its second operand and produces a result
true or false based on the condition. It also lets the developer to create their own type classes having
runtime behavior specified by the developer. aMoneyType, aDateType, aCheckingAccountID, etc are
some to the examples of the such type of classes.
Syntax: Here is the syntax for using an instanceOf keyword
if (node instanceof TreeNode){
Where, condition (node instanceOf TreeNode) returns true if the class node is an instance or is an
instance of a subclass of TreeNode.
Example: Here is the example how the instanceOf operator is used.
It returns the output "is a String" after checking the condition because the condition returns true.
Note: Here are some points which must be noted.
While applying the instanceOf operator on a null reference then it returns false.