on Leave a Comment

instanceof operator in Java

The java instanceof operator is a object reference operator that returns a boolean value either true or false. If the reference is the instance of specified type, it returns true otherwise it returns false. Java instanceof operator is also known as type comparision operator because it compares the reference with specified type.

Java instanceof operator can be used to check the runtime information of an object. This operator is very useful in the case of typecasting of an object.

Example of Java instanceof Operator

class Example
{
 public static void main(String[] args) {
  Example obj = new Example();

  System.out.println(obj instanceof Example);
 }
}

Output:

true

Java instanceof operator - What happens when a reference has null value?

class Example
{
 public static void main(String[] args) {
  Example obj = null;

  System.out.println(obj instanceof Example);
 }
}

Output:

false

Downcasting with java instanceof operator

class Question
{

}

class Answer extends Question
{
 static void show()
 {
  System.out.println("Ok Downcasting Performed");
 }
 static void test(Question o)
 {
  if(o instanceof Answer)
  {
            Answer ob = (Answer)o; //Downcasting
   show();
  }
 }
 public static void main(String[] args) {
  Question obj = new Answer();

  Answer.test(obj);
 }
}

Output:

Ok Downcasting Performed

Another Example of Java instanceof Operator

class A
{}

class B extends A
{
 public void show()
 {
  System.out.println("Class B");
 } 
}
class C extends A
{
 public void show()
 {
  System.out.println("Class C");
 } 
}
class Example extends Testing
{
    static void check(A obj)
    {
     if(obj instanceof B)
     {
      B b = (B)obj;
      b.show();
     }
     else
     {
      C c = (C)obj;
      c.show();
     }
    }
 public static void main(String[] args) {
  A obj = new B();
        
        Example.check(obj);
 }
}

Output

Class B

0 comments:

Post a Comment