The instanceof keyword in Java is used to test whether an object is an instance of a specific class or interface. It is a binary operator that returns a boolean value: true if the object is an instance of the specified type, and false otherwise.
Table of Contents
- Introduction
instanceofKeyword Syntax- Understanding
instanceof - Examples
- Basic Usage
- Checking Against Interfaces
- Using
instanceofwith Patterns (Java 16+)
- Real-World Use Case
- Conclusion
Introduction
The instanceof keyword is used in Java for type checking. It is commonly used in scenarios where the type of an object is not known at compile time, such as in polymorphic code or when dealing with heterogeneous collections.
instanceof Keyword Syntax
The syntax for using the instanceof keyword is straightforward:
object instanceof ClassName
Example:
if (obj instanceof String) {
String str = (String) obj;
// Use str
}
Understanding instanceof
Key Points:
- Type Checking: Checks if an object is an instance of a specified class or implements a specified interface.
- Null Safety: Returns
falseif the object isnull. - Class Hierarchy: Can be used to check instances of subclasses or implementations of interfaces.
Examples
Basic Usage
A simple example demonstrating the use of instanceof for type checking.
Example
public class Main {
public static void main(String[] args) {
Object obj = "Hello, World!";
if (obj instanceof String) {
String str = (String) obj;
System.out.println("The object is a string: " + str);
} else {
System.out.println("The object is not a string.");
}
}
}
Output:
The object is a string: Hello, World!
Checking Against Interfaces
Using instanceof to check if an object implements a specific interface.
Example
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Bark");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.sound();
} else {
System.out.println("The animal is not a dog.");
}
}
}
Output:
Bark
Using instanceof with Patterns (Java 16+)
Java 16 introduced pattern matching for instanceof, which simplifies type checks and variable declarations.
Example
public class Main {
public static void main(String[] args) {
Object obj = "Hello, World!";
if (obj instanceof String str) {
System.out.println("The object is a string: " + str);
} else {
System.out.println("The object is not a string.");
}
}
}
Output:
The object is a string: Hello, World!
Real-World Use Case
Polymorphic Collections
In real-world applications, instanceof is often used to handle collections of objects with different types.
Example
import java.util.ArrayList;
import java.util.List;
class Shape {
}
class Circle extends Shape {
void draw() {
System.out.println("Drawing a circle");
}
}
class Square extends Shape {
void draw() {
System.out.println("Drawing a square");
}
}
public class Main {
public static void main(String[] args) {
List<Shape> shapes = new ArrayList<>();
shapes.add(new Circle());
shapes.add(new Square());
for (Shape shape : shapes) {
if (shape instanceof Circle) {
((Circle) shape).draw();
} else if (shape instanceof Square) {
((Square) shape).draw();
}
}
}
}
Output:
Drawing a circle
Drawing a square
Conclusion
The instanceof keyword in Java is a versatile tool for type checking, allowing developers to determine the type of an object at runtime and perform appropriate actions based on its type. With the introduction of pattern matching for instanceof in Java 16, this keyword has become even more powerful and concise. Understanding and using instanceof effectively is essential for writing robust and type-safe Java applications.