The instance of keyword
The keyword instanceOf in java programming language is a boolean operator that is used to test whether an object is of an specified type or not and returns the value accordingly. Keywords are basically reserved words which have specific meaning relevant to a compiler. It takes an object 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){ / write your code here } |
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.
public class MainClass {
|
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.