Instanceof in Java

Instanceof Java Operator: Java is a popular programming language widely used in various applications and industries. One of the unique features of Java is its “instanceof” operator, which is used to check whether an object belongs to a particular class or its subclass. This operator is a powerful tool for developers, as it allows them to perform various operations based on the type of object they are dealing with.

In this article, we will explore the instanceof an operator in detail, its syntax, usage, and some practical examples of how it can be used in Java programming. We will also discuss some common mistakes developers make while using this operator and how to avoid them. So, whether you are a beginner or an experienced Java developer, this article will provide valuable insights into the instance of the operator and how to use it effectively in your code.

Post Type:Core Java Tutorial
Published On:www.softwaretestingo.com
Applicable For:Freshers & Experience
Get Updates:Join Our Telegram Group

The instanceof operator in Java is often used with other programming constructs, such as if-else statements, switch statements, and loops. It allows developers to check the type of an object at runtime and perform operations based on its class or subclass. This is particularly useful in scenarios where the type of an object is not known at compile-time but is determined at runtime.

For example, in a program that deals with different types of animals, the instance can be used to check if an object is an instance of a particular animal class, such as “Dog” or “Cat,” and perform specific actions accordingly.

Java Instanceof Syntax

The syntax for using the instanceof operator in Java is straightforward. It involves using the object reference followed by the keyword “instanceof” and the class name to which the object is being compared. The syntax looks like this:

object_name instanceof class_name;

Here, “object_name” represents the object reference being checked, and “class_name” represents the class or subclass the object is being compared to. The instance of the operator returns a boolean value of either true or false, depending on whether the object is an instance of the specified class or subclass.

It is important to note that the instanceof operator can only be used with object references and not with primitive data types such as int, float, or boolean. Additionally, it can only be used with classes and interfaces, not enums or annotations.

Instanceof in Java Example

Earlier in this post, we have seen the syntax of the Instanceof in Java. From now on, we will see some examples to understand the concept of Instanceof of Java in detail. For better understanding, we came up with examples based on their implementation.

Example 1: Basic Use

package com.softwaretestingo.Basic;
public class InstanceOfEx1 
{
	public static void main(String[] args) 
	{
		String abc="Hello World";
		if(abc instanceof String) 
		{
		   System.out.println("abc is an instance of String");
		} 
		else 
		{
		   System.out.println("abc is not an instance of String");
		}
	}
}

Output:

abc is an instance of String

In this basic example, we declare a string object and initialize it with a value. We then use the instanceof operator to check if the object reference is an instance of the String class. Since we have initialized the object reference with a String object, the output of this program will be “abc is an instance of String.”

Example 2: Checking Subclasses

package com.softwaretestingo.basic;
class Animal
{
	public void makeSound() 
	{
		System.out.println("The animal makes a sound");
	}
}
class Dog extends Animal 
{
	public void makeSound() 
	{
		System.out.println("The dog barks");
	}
}
public class InstanceOfEx2
{
	public static void main(String[] args) 
	{
		//We Can call any method of Dog class using animal reference
		//Upcasting Example
		Animal animal = new Dog();
		
		if(animal instanceof Dog) 
		{
			Dog dog = (Dog) animal;
			dog.makeSound();
		}
	}
}

Output:

The dog barks

In this example, we have defined two classes: Animal and Dog. The dog is a subclass of Animal, which means it inherits all the properties and methods of the Animal class. In the main method, we create a new Dog object and assign it to an Animal reference variable. We then use the instanceof operator to check if the Animal object is an instance of the Dog class. Since we have initialized the Animal reference variable with a Dog object, the output of this program will be “The dog barks.”

If you are slightly confused about casting, you can watch the video below.

Java Instanceof in Java

Example 3: Checking Interface Implementations

The instanceof operator allows us to check whether the object of a subclass is an instance of a superclass.

package com.softwaretestingo.basic;
interface Vehicle_interface 
{
	public void drive();
}
class Car implements Vehicle_interface 
{
	public void drive() 
	{
		System.out.println("The car is driving");
	}
}
public class InstanceOfEx3
{
	public static void main(String[] args) 
	{
		Vehicle_interface vehicle = new Car();
		if(vehicle instanceof Vehicle_interface) 
		{
			vehicle.drive();
		}
	}
}

Output:

The car is driving

In this example, we define an interface called Vehicle_interface and a class called Car that implements the Vehicle_interface interface. In the main method, we create a new Car object and assign it to a Vehicle_interface reference variable. We then use the instanceof operator to check if the object reference is an instance of the Vehicle interface. Since Car implements the Vehicle interface, the output of this program will be “The car is driving.”

Example 4: Advanced Use

The purpose of the instance of the operator is to check if an object belongs to a certain class or interface. It returns true if the object is an instance of that class/interface.

package com.softwaretestingo.Basic;
abstract class Shape 
{
	abstract void draw();
}
class Rectangle extends Shape 
{
	void draw() 
	{
		System.out.println("Drawing a rectangle");
	}
}
class Circle extends Shape 
{
	void draw() 
	{
		System.out.println("Drawing a circle");
	}
}
public class InstanceOfEx4
{
	public static void main(String[] args) 
	{
		Shape[] shapes = {new Rectangle(), new Circle()};
		for(Shape shape : shapes) 
		{
			if(shape instanceof Circle) 
			{
				Circle circle = (Circle) shape;
				circle.draw();
			} 
			else 
			{
				Rectangle rectangle = (Rectangle) shape;
				rectangle.draw();
			}
		}
	}
}

In this example, we have defined an abstract class called Shape and two concrete subclasses, Rectangle and Circle, that extend the Shape class. In the main method, we create an array of Shape objects that contains a Rectangle and a Circle object. We then loop through each Shape object in the array and use the instanceof operator to determine whether it is an instance of the Circle or Rectangle class.

Depending on the result, we cast the Shape object to the appropriate subclass and invoke its draw() method. Since both the Rectangle and Circle classes inherit the abstract draw() method from the Shape class, the output of this program will be “Drawing a rectangle” and “Drawing a circle.

This example showcases the flexibility of the instanceof the operator to check the type of an object at runtime and perform different operations based on its class or subclass. In this case, we can use the instanceof operator to determine the class of each Shape object in the array and cast it to the appropriate subclass to invoke its unique draw() method.

Overall, these examples demonstrate the versatility of the instanceof operator in Java and how it can be used to perform various tasks, from basic type checking to more complex operations involving subclasses and interfaces. By using the instanceof operator effectively, developers or automation testers can write more flexible and robust Java code that can adapt to changing runtime conditions and requirements.

Conclusion:

The instanceof operator is a powerful feature of the Java programming language that allows developers to check the type of an object at runtime and perform operations based on its class or subclass. Its ability to dynamically determine an object’s type makes it an essential tool for building robust and flexible Java applications. By understanding the syntax and usage of the instanceof operator, developers can write more efficient and effective Java code and avoid common pitfalls that may arise while using this operator.

In this blog post, we have tried to cover the Java InstanceOf Keyword operator in detail with an example. Let me know if you find something missing about the Java InstanceOf. Then, you can inform us by commenting in the comment section.

Avatar for Softwaretestingo Editorial Board

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment