instanceof keyword in java
The ” instanceof
” keyword is used to check whether an object is an instance of a particular class or interface
The instanceof
in java is also known as type comparison operator because it compares the object or instance with type.It returns either true or false.
Example
- Object score = new Integer(98);
- if (score instanceof Integer) {
- System.out.println("score is an integer");
- }
- else{
- System.out.println("score is not an integer");
- }
Object score = new Integer(98); if (score instanceof Integer) { System.out.println("score is an integer"); } else{ System.out.println("score is not an integer"); }
In the above example, score variable is holding reference to Integer object at run time and hence instanceof returns true.
- Object score = new Double(98.5);
- if (score instanceof Integer) {
- System.out.println("score is an integer");
- }
- else{
- System.out.println("score is not an integer");
- }
Object score = new Double(98.5); if (score instanceof Integer) { System.out.println("score is an integer"); } else{ System.out.println("score is not an integer"); }
In the above example, score variable is holding reference to Double object at run time and hence instanceof returns false.
If we apply the instanceof operator with any variable that has null value, it returns false.
Example
- Object score = null;
- if (score instanceof Integer) {
- System.out.println("score is an integer");
- }
- else{
- System.out.println("score is not an integer");
- }
Object score = null; if (score instanceof Integer) { System.out.println("score is an integer"); } else{ System.out.println("score is not an integer"); }
An object of subclass type is also a type of parent class.
For example, if Car extends Vehicle then object of Car can be referred by either Car or Vehicle class.
- class Vehicle{
- }
- class Car extends Vehicle{//Car inherits Vehicle
- public static void main(String args[]){
- Car c=new Car();
- System.out.println(c instanceof Car);//true
- System.out.println(c instanceof Vehicle);//true
- }
- }
class Vehicle{ } class Car extends Vehicle{//Car inherits Vehicle public static void main(String args[]){ Car c=new Car(); System.out.println(c instanceof Car);//true System.out.println(c instanceof Vehicle);//true } }
But the other way is not correct, An object of super class type is not a type of sub class.
Example
Object of Vehicle is not a type of Car as below
- public static void main(String args[]){
- Vehicle v=new Vehicle();
- System.out.println(v instanceof Car);//false
- System.out.println(v instanceof Vehicle);//true
- }
- }
public static void main(String args[]){ Vehicle v=new Vehicle(); System.out.println(v instanceof Car);//false System.out.println(v instanceof Vehicle);//true } }