Friday, 19 December 2014

What is instanceof Operator in java ?


The  instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface) and it return Boolean value

The instanceof operator is also known as type comparison operator because it compares the instance with type. It returns either true or false. If we apply the instanceof operator with any variable that have null value, it returns false.

Simple example of instanceof operator:

Let's see the simple example of instance operator where it tests the current class.

class Test{

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

Output: true

An object of subclass type is also a type of parent class.For example, if Person extends Student then object of Person can be reffered by either Person or Student class.

Another example of instanceof operator:

class Person{ }
class Student extends Person  {  //Student inherits Person

public static void main(String []args){
Student s=new Student();
System.out.println(s instanceof Person);
  }
}

Output: true

instanceof operator with a variable that have null value:

If we apply instanceof operator with a variable that have null value, it ruturns false.
Let's see the example given below where we apply instanceof operator with the variable that
have null value.

For example:

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

Output: false



No comments:

Post a Comment