×

Instanceof operator in Java

To determine whether an object is an instance of the supplied type in Java, use the instanceof operator (class or subclass or interface).

Because it compares the instance with type, the instanceof operator in Java is also known as a type comparison operator. Either true or false is returned. Any variable that has a null value when the instanceof operator is used returns false.

Program 1 for Simple java instanceof

Example1.java

class Example1{  
 public static void main(String args[]){  
 Example1 simple=new Example1();  
 System.out.println(simple instanceof Example1);
 }  
}  

Output

instanceof operator in Java

Program 2 for java instanceof

Cat.java

class Cat extends Animal{ 
 public static void main(String args[]){  
 Cat c=new Cat();  
 System.out.println(c instanceof Animal);
 }  
}  
class Animal{}

Output

instanceof operator in Java

Program 3 for java instanceof

Cat.java

class Cat{  
 public static void main(String args[]){  
  Cat c=null;  
  System.out.println(c instanceof Cat);  
 }  
}  

Output

instanceof operator in Java

Downcasting with Java instanceof operator

Downcasting occurs when a subclass type refers to an object of the parent class. If we try to execute it immediately, the compiler returns an error. A ClassCastException is thrown at runtime if you typecast it. However, downcasting is doable if we utilise the instanceof operator.

Cat c=new Animal();

When typecasting is used to downcast, a ClassCastException is thrown at runtime.

Dog d=(Dog)new Animal(); 

Program 4 for Java instanceof with DownCasting

Cat.java

class Animal { }    
class Cat extends Animal {  
  static void method(Animal cat) {  
    if(cat instanceof Cat){  
       Cat c=(Cat)cat;
       System.out.println("Downcasting is performed");  
    }  
  }  
  public static void main (String [] args) {  
    Animal cat=new Cat();  
    Cat.method(cat);  
  }  
    
 }  

Output:

instanceof operator in Java

Downcasting without the use of Java instanceof

Program 5 for Java instanceof with DownCasting

Cat.java

class Animal { }  
class Cat extends Animal {  
  static void method(Animal cat) {  
       Cat c=(Main)cat;
       System.out.println("Downcasting is performed");  
  }  
   public static void main (String [] args) {  
    Animal cat=new Cat();  
    Cat.method(cat);  
  }  
}  

Output:

instanceof operator in Java

Real-world Java instanceof usage with an example program

Program 6 for Java instanceof

Test.java

interface Print{}  
class First implements Print{  
public void first(){System.out.println("First method");}  
}  
class Second implements Print{  
public void second(){System.out.println("Second method");}  
}  
  
class call_method{  
void invoke_method(Print p1){
if(p1 instanceof First){  
First first=(First)p1;  
first.first();  
}  
if(p1 instanceof Second){  
Second second=(Second)p1;
second.second();  
}  
  
}  
}
  
class Test{  
public static void main(String args[]){  
Print p1=new Second();  
call_method c1=new call_method();  
c1.invoke_method(p1);  
}  
}  

Output:

instanceof operator in Java

Program 7 for Java instanceof

Test1.java

class Parent {}
class Son extends Parent {}
class Test1 {
public static void main(String[] args)
    {
        Son s1 = new Son();
        if (s1 instanceof Son)
            System.out.println("s1 is instance of Son");
        else
            System.out.println(
                "s1 is NOT instance of Son");
        if (s1 instanceof Parent)
            System.out.println(
                "s1 is instance of Parent");
        else
            System.out.println(
                "s1 is NOT instance of Parent");
        if (s1 instanceof Object)
            System.out.println(
                "s1 is instance of Object");
        else
            System.out.println(
                "s1 is NOT instance of Object");
    }
}

Output:

instanceof operator in Java

Program 8 for Java instanceof

Test3.java

class Parent
{
    int v1 = 30000;
}
 
class Son extends Parent
{
    int v1 = 20;
}
class Test3
{
    public static void main(String[] args)
    {
        Parent s1 = new Son();
        Parent p1 = s1;
        if (p1 instanceof Son)
        {
            System.out.println("The value accessed by " +
                "the parent reference via typecasting is " +
                                     ((Son)p1).v1);
        }
    }
}

Output:

instanceof operator in Java

Program 9 for  Java instanceof

Example1.java

class Example1 {
  public static void main(String[] args) {
    String str = "My instanceof example";
    boolean r1 = str instanceof String;
    System.out.println("str is an instance of String: " + r1);
    Example1 object1 = new Example1();
    boolean r2 = object1 instanceof Example1;
    System.out.println("object1 is an instance of Test: " + r2);
  }
}

Output:

instanceof operator in Java

Related Topics

String Manipulation in Java

String Manipulation in Java In Java, string manipulation is a common task performed by programmer. Java String class provides many built-in functions that are used to manipulate string. The manipulation of...

4 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Integer numberOfLeadingZeros() method

The numberOfLeadingZeros()  method of Java Integer class returns the total number of zero bits preceding the highest-order one-bit in the 2’s complement binary representation of the specified int value.  Syntax public static...

1 minute read.

Bin Packing Problem Java

Assigning some items with known weights to bins with consistent capacities is necessary for the bin packing problem. The goal is to use the smallest possible boxes while ensuring everything is put...

6 minutes read.

How to handle NullPointerException in Java

Introduction: Throwable class is the super or root class of the java exception hierarchy which contains two sub-classes. The classes’ are- ExceptionError Exception: If you are doing any wrong things in a...

3 minutes read.

House Numbers in Java

In this section, we will discuss about house number in Java. It is a sum of cubes, each of which has a dimension of h + 1. There is a...

3 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Practical Number in Java

In this tutorial, we will understand what is meant by practical numbers. We will understand it throughthe aid of examples and implementation in a java programming language. The practical numbers...

5 minutes read.

Java Try Keyword

The try block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java try block has...

3 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Sparse Numbers in Java

In this section, we will be very well acknowledged about the sparse numbers in Java, how a number can be verified if it is a sparse number or not. Sparse Numbers Any...

3 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Java Program to remove duplicate characters in a string

In strings, we can find many characters present one or more times in a string; accessing a particular character is difficult due to repetition. Duplicate characters will present in the...

5 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.