×

Java Programs

Java Practice

Java program to check whether an object belongs to a particular class or not

Java example to check whether an object belongs to a particular class or not.
Submitted by Nidhi, on April 29, 2022

Problem statement

In this program, we will check whether an object belongs to a particular class or not using the isInstance() method. The isInstance() returns a Boolean value.

Java program to check whether an object belongs to a particular class or not

The source code to check whether an object belongs to the particular class or not is given below. The given program is compiled and executed successfully.

// Java program to check whether an object belongs 
// to a particular class or not

public class Main {
  public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    Class cls = Class.forName("Main");

    Main m = new Main();
    int val = 50;

    boolean res1 = cls.isInstance(m);
    boolean res2 = cls.isInstance(val);

    System.out.println("Is m instance of Main   : " + res1);
    System.out.println("Is val instance of Main : " + res2);
  }
}

Output

Is m instance of Main   : true
Is val instance of Main : false

Explanation

In the above program, we created a public class Main that contains a main() method. The main() method is the entry point for the program. Here, we checked whether an object belongs to the particular class or not using the isInstance() method. The isInstance() method returns true if the specified object belongs to the class otherwise it returns false. And, checked created objects belonged to the Main class or not and printed the appropriate result.

Java Class and Object Programs »



Related Programs



Comments and Discussions!

Load comments ↻





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