What is the purpose of the ‘instanceof’ keyword in Java?

Java MCQ: What is the purpose of the ‘instanceof’ keyword in Java?

a) To check if an object is an instance of a class or subclass
b) To cast an object to a different type
c) To compare two objects for equality
d) To create a new instance of a class

Answer:

a) To check if an object is an instance of a class or subclass

Explanation:

The instanceof keyword in Java is used to check whether an object is an instance of a specific class or a subclass of that class. It is a boolean operator that returns true if the object is an instance of the specified type and false otherwise.

This keyword is particularly useful in scenarios where you need to ensure that an object is of a certain type before performing operations on it. For example, it can be used in type-checking before casting an object to a specific type to avoid ClassCastException.

Understanding the instanceof keyword is important for type safety in Java, helping developers write robust and error-resistant code.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top