×

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

Economical number in Java

Economical number is said to be economically efficient if the number of digits after prime factorization of the original number with their powers is less than the number of digits...

3 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

Java Socket Programming

Java Socket Programming Socket programming is used for the communication between the applications, i.e., client and server running on different JRE may be connection-oriented or connectionless. The client program can be designed using the...

8 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Polygonal Number in Java

What does a Java Polygonal Number Mean? In mathematics, a polygonal number refers to a number that is expressed through dots or pebbles arranged in a regular polygonal pattern. Alphas are...

4 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Difference Between BufferedReader and FileReader

BufferedReader: To read data from a specified character stream, two classes are used: buffered readers and file readers. Both of them have advantages and disadvantages. Although how they operate is the...

6 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Java Integer numberOfTrailingZeros() method

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

1 minute read.

How to Convert String to long in Java

How to Convert String to long in java It is used when you want to perform the mathematical operation on the String which contains long number then the conversion from String...

4 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Java Strictfp Keyword

Strictfp is used to impose limits on floating-point calculation. It ensures that we will get the same result on every platform while performing an operation with the floating-point variable. The floating-point calculation is platform-dependent due...

1 minute read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Insertion Sort in Java

Insertion Sort in Java Insertion sort in Java is a simple sorting algorithm that works in the same way as we hold cards in hand. Insertion sort does the sorting element-by-element,...

3 minutes read.