instanceof operator in Java

instanceof operator is used to check whether an object is an instance or object of a particular class.

General Syntax

object_name instanceof class_name

It returns true when the object is instance of that class and false when it is not an instance.

It is also called as type comparison operator.

It is used largely in if statements.

Example 1

class Car{

static int wheels=4;

}

class CarMain{

public static void main(String args[]){

Car benz=new Car();

if(benz instanceof Car){

System.out.println("benz is instance of car.");

}

}

}

Try In Editor

Output

benz is instance of car.


Example 2

class Vehicle{

float max_speed=500.88f;

}

class Car extends Vehicle{

static int wheels=4;

}

class CarMain{

public static void main(String args[]){

Car benz=new Car();

if(benz instanceof Vehicle){

System.out.println("benz is instance of Vehicle.");

}

}

}

Try In Editor

Output

benz is instance of Vehicle.