object instanceof ClassName
object
: The reference variable pointing to the object being tested.
ClassName
: The class or interface that you want to check the type of the object against.
class Animal
{
// some methods
}
class Dog extends Animal
{
// some methods
}
public class InstanceOfExample
{
public static void main(String[] args)
{
Animal animal = new Dog(); // Animal reference, but Dog object
// Using instanceof to check the type
if (animal instanceof Dog)
{
System.out.println("The animal is a Dog");
}
else
{
System.out.println("The animal is not a Dog");
}
}
}
The animal is a Dog
instanceof
Operator:
String str = "Hello";
System.out.println(str instanceof String); // Output: true
List<String> list = new ArrayList<>();
System.out.println(list instanceof List); // Output: true
instanceof
operator will always return false
when the object being checked is null
.
String str = null;
System.out.println(str instanceof String); // Output: false
instanceof
:
class Animal {}
class Dog extends Animal {}
Animal a = new Dog();
System.out.println(a instanceof Dog); // Output: true
System.out.println(a instanceof Animal); // Output: true
instanceof
operator also works with interfaces. It checks if an object implements a specific interface.
interface Playable {}
class Football implements Playable {}
Playable game = new Football();
System.out.println(game instanceof Playable); // Output: true
instanceof
operator is generally fast as it is a runtime check.
Object
class. This is efficient but can cause slight overhead in complex hierarchies.
instanceof
with switch
(Java 16+):
instanceof
can be used in a switch
statement with pattern matching.
Object obj = new Dog();
switch (obj) {
case Dog d -> System.out.println("It's a dog!");
case Cat c -> System.out.println("It's a cat!");
default -> System.out.println("Unknown animal");
}
instanceof
with Type Casting:
instanceof
operator is often used in conjunction with casting to safely cast objects.
Object obj = "Hello";
if (obj instanceof String) {
String str = (String) obj; // Safe cast
System.out.println(str.length()); // Output: 5
}
instanceof
with Generics:
instanceof
operator can be used with generics, but due to type erasure in Java, it can only check the raw type of the generic class.
List list = new ArrayList<>();
if (list instanceof ArrayList) {
System.out.println("It's an ArrayList");
}
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weโre here to make our tutorials better based on your thoughts and suggestions.