×

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

Type Annotations in Java

Only declarations were eligible for annotations in earlier versions of Java. With Java 8, you may now annotate any type use, including types in declarations, generics, and casts: @Encrypted String data; List<@NonNull...

6 minutes read.

How to check version of java in Linux

Java is one of the most famous and thoroughly utilized programming tongues from one side of the world to the other. On the off chance that you are a Java...

2 minutes read.

Java Queue Interface

Queue interface is a subtype of Collection interface. All methods in the Collection interface are also available in the Queue interface. It provides operations of Collection and also some additional...

2 minutes read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

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.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

Java Integer class

The Integer class wraps a primitive int type value in an object. Its object contains only a single field whose type is int. Methods: The java.lang.Integer class provides several different methods for...

4 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

java.lang.NumberFormatException for Input String

java.lang.NumberFormatException for Input String The exception java.lang.NumberFormatException for input string occurs when we try to convert a string into a number format. For example, if someone converts the string “Tutorial & Example”...

3 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Java String format() method

format() method returns a formatted String based on the given locale,specified format and arguments. Syntax: public static String format(String format , Object… args) Parameter: locale : It specifies locale value to be applied on...

2 minutes read.

Java Comparator Interface

Java comparator interface is used in a situation when we have to sort an object which does not implement Comparable or do sorting in a different way than the Comparable....

1 minute read.

Java Math sqrt() Method

The sqrt() method of Java Math class returns the accurately rounded positive square root of the specified double value. Syntax: public static double sqrt(double a) Parameters: The parameter ‘a’ represents the number whose square...

2 minutes read.

Add numbers represented by Linked Lists in Java

For calculating the sum of the two numbers that are represented by a linked list, and then store the result in a new linked list. A linked list's head node...

7 minutes read.