Write a Java program to demonstrate the instanceof operator


The program defines a class named Demo. In the main method of this class, a new object of type Demo is created using the default constructor. Then, the instanceof operator is used to check if the object d is an instance of the Demo class. If the object is an instance of the class, the program prints the message "Object d is an instance of Demo class". Otherwise, it prints the message "Object d is not an instance of Demo class".

The instanceof operator is used to test if an object is an instance of a particular class, a subclass of that class, or a class that implements a particular interface. It returns a boolean value indicating whether the object is an instance of the specified type. In this program, the operator is used to check if the object d is an instance of the Demo class.

Source Code

public class Demo
{
	public static void main(String[] args)
	{
		Demo d = new Demo();
		boolean res = d instanceof Demo;
		if (res)
		{
			System.out.println("Object d is an instance of Demo class");
		}
		else
		{
			System.out.println("Object d is not an instance of Demo class");
		}
	}
}

Output

Object d is an instance of Demo class