Java Program on instanceOf Operator

In the previous article we have discussed about Java Program on Bitwise XOR Operator

In this article we will see the use of instanceOf operator in Java programming language.

Java Program on instanceOf Operator

instanceOf operator:

instanceOf operator in Java checks whether an object is an instance of a particular type (i.e. object of class or subclass or interface).

Syntax:

objName instanceOf objRefType;

Where,

  • objName refers to the name of object or the reference variable.
  • instanceOf refers to the operator.
  • objRefType refers to the type of object reference i.e class, subclass or interface.

If the reference variable/obect (i.e objName) is an instance of specified object reference type (i.e. objRefType) then it returns True else it returns False.

Example program-1:

class Main 
{
  public static void main(String[] args) 
  {
    // create a variable of integer type
    String statement = "You are learning from BtechGeeks";
    
    // checks if statement is instance of String type
    // it will return True
    boolean output1 = statement instanceof String;
    System.out.println("statement is an instance of String: " + output1);
  }
}
Output:

statement is an instance of String: true

Example program-2:

class Main 
{
  public static void main(String[] args) 
  {
    //creating object of class Main
    Main m = new Main();
    //checking reference variable 'm' refers to reference Type class 'Main' or not
    boolean output = m instanceof Main;
    System.out.println("m is an instance of Main: " + output);
  }
}
Output:

m is an instance of Main: true

Are you a job seeker and trying to find simple java programs for Interview? This would be the right choice for you, just tap on the link and start preparing the java programs covered to crack the interview.

Related Java Programs: