Java program to demonstrate the instanceof operator

Write a Java program to demonstrate the example of instanceof operator.
Submitted by Nidhi, on March 24, 2022

Problem Solution:

In this program, we will check an object of an instance of a particular class or not using "instanceof" operator. It returns the Boolean value true, false.

Program/Source Code:

The source code to demonstrate the "instanceof" operator is given below. The given program is compiled and executed successfully.

// Java program to demonstrate the example of 
// "instanceof" operator

public class Main {
  public static void main(String[] args) {
    Main m = new Main();

    boolean ret = m instanceof Main;

    if (ret)
      System.out.println("The Object m is an instance of Main class");
    else
      System.out.println("The Object m is not an instance of Main class");
  }
}

Output:

The Object m is an instance of Main class

Explanation:

In the above program, we created a class Main. The Main class contains a method main(). The main() method is an entry point for the program. Here, we created the object m of Main() class and checked 'm' is an instance of class Main or not using the "instanceof" operator and printed the appropriate message.

Java Class and Object Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.