×

Java Instanceof Keyword

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

The type of comparison in java differentiates the instance with type that is why instanceof operator in Java is also called as a type of comparison operator.  True or false is returned in the program. The variable that has a zero-value assigned to it when the instanceof operator is implemented in returning false value.

 Simple example of java instanceof

class II1{  
 public static void main (String s[]) {
II1 h=new II1();
 System.out.println(s instanceof II1) ;//true  
 }  
}  

Output:

True

To an object a type of parent class is also implemented of subclass type. For instance, if Dog extends Animal, then either the Dog class or the Animal class may refer to an object of Dog.

Another example of java instanceof operator:

class Aml {}  
class D1 extends Aml {/ Animal inherited dog


 public static void main (String s[]) {
 D1 k=new D1();
 System.out.println(k instanceof Aml) ;//true  
 }  
}  

Output:

true

Instanceof in java with a variable that have null value

The instanceof operator returns false when used on a variable that has no value. Look at the example below where the instanceof operator is used with a variable that has no value.

class D2{  
 public static void main (String s []) {
  D2 k=null;
  System.out.println(k instanceof D2) ;//false  
 }  
}  

Output of the given program is:

False

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.

Do h=new Aml () ;//Compilation error  
When downcasting is implemented, a ClassCastException is thrown at runtime.
Do h=(Do)new Aml ();
// ClassCastException is thrown at runtimebut execution is succesfull.

Possibility of downcasting with instanceof

Let's see the example, where downcasting is possible by instanceof operator.

class Aml {}


class Do3 extends Aml {  
  static void method (Aml a) {  
if (a instanceof Do3) {
       Do3 k=(Do3) a;//downcasting  
       System.out.println("downcasting is performed in program ");
    }  
  }  
  public static void main (String [] s) {  
    Aml a=new Do3();
    Do3.method(a);
  }  


 }  

Output of the program is:

downcasting is performed in program

Downcasting without the use of java instanceof

As shown in the example below, downcasting can also be done without the instanceof operator:

class Aml {}
class D4 extends Aml {  
  static void method (Aml a) {  
       D4 d=(D4) a;//downcasting  
       System.out.println("downcasting is performed in program ");
  }  
   public static void main (String [] s) {  
    Aml a=new D4();
    D4. method(a);
  }  
}  

Output:

ok downcasting performed

Let's look at this more closely. The actual object to which an refers is an object of the Dog class. So, it's okay if we downcast it. However, what will occur if we write:

Aml a=new Aml ();
Dogee.method(a);
//Now ClassCastException but not in case of instanceof operator

Understanding Real use of instanceof in java

An example using  or implmenting the instanceof word is in practise of real example.

interface exe {}  
class R implements exe {
public void r() {System.out.println("r method");}  
}  
class S implements exe {  
public void s (){System.out.println("s method");}  
}  


class Cal {
void wake (exep) {//upcasting  
if (p instanceof A) {
Rr=(R)p;//Downcasting   
r.r();
}  
if (p instanceof S) {
Ss=(S)p;//Downcasting   
s.s();
}  


}  
}//end of Call class  


class T4{  
public static void main (String s []) {
Printable p=new S ();
Cal J=new Cal ();
J. invoke(p);
}  
}  

Output:

S method

Instanceof Operator

To determine whether an object belongs to a specific type, we utilise the binary operator instanceof. Either true or false is the outcome of the procedure. It compares the instance with the type, which is why it is also referred to as a type of comparison operator.

It is usually advisable to use the instanceof check before casting an unidentified object. By doing this, a runtime ClassCastException is reduced.

Instanceof Operator Work

The instanceof operator implemented on the rules of is-a relationship. The conclusion concept of an is-a relationship is depended on class of parent and child or interface implementation

We'll build a Shape interface to execute this:

public interface symbol {
    // implementation details
}
Additionally building a class of a Circle that implements the round class and implements the Shape interface that is been used.

public class Circle extends Round implements Symbol{// details of implementation of circle}

Test public void givenWhenObjectIsInstanceOfType_thenReturnTrue () {Circle c = new Circle (); Assert.assertTrue (c instanceof Circle);}


Related Topics

How to take Array Input in Java

In this tutorial, we will learn about how to take array input in Java. So, before taking inputs let us know what an array is first. Array: An array is a collection...

10 minutes read.

Java finally

Java finally: There are some statements in a program whose execution is extremely important. For example, closing of a database connection. Statements that do the closing of the database connection...

5 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Difference between Constructor and Method in Java

What is Constructor? In Constructor, we will discuss constructors and also will discuss default constructors and finally, we will discuss overloading constructors. A constructor is a method that is used to...

13 minutes read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Java Binary Tree

The non-linear data structure known as a binary tree is a type of tree, and because it stores data in a hierarchical manner, it is mostly utilised for finding and...

7 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Perfect Number Program in Java

Perfect Number Program in Java A perfect number is a number whose sum of all the factors, excluding the number itself, is equal to the number. For example, 28 is a...

4 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute 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.

Group by in Java 8

By using this groupingBy() method, developers can directly able to perform the "GROUP BY" operation. The thing is, now, the Java 8 programming language allows the programmers to do this...

3 minutes read.

How to Create a Generic List in Java?

Generics are types that have parameters. The goal is to make it possible for methods, classes, and interfaces to take type (Integer, String, etc., and user-defined types) as a parameter....

4 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Java Variable

The variable is the basic unit of storage in a program. We define a variable using an identifier, a type, and an optional initializer in Java. In Java, variables must be...

4 minutes read.

Java class class

Java Class class instances are an executing Java application's implementation of the classes and interfaces. As well as, every Array is indeed an object that is common for all Arrays...

6 minutes read.