What is instanceOf operator ? Explain it's use ?
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Interview Questions and Answers

Usually asked in relation to casting and ClassCastException.
 Q1. What is instanceOf operator ? Explain it's use ?Core Java
Ans. The operator instanceOf is used to verify if the specified object is the instance of specified class or interface.

Syntax if(x instanceOf ABC)

where x is an object reference and ABC could be a class name or interface name. The above statement will be true if x holds an object that is an instance of ABC or any of the child class of ABC or if x holds an object that implements ABC.

instanceOf operator is used to verify in case of downcasting. For ex -

DerivedClass extends BaseClass

x is the reference of BaseClass but holds DerivedClass object ( Polymorphism )

There is an operation that is defined in Derived Class, let's say derivedClassMethod()

We cannot call derivedClassMethod() directly using x as x is reference of BaseClass and not DerivedClass and hence can only access methods that are defined in BaseClass and overridden in derived class.

Though we can cast it to DerivedClass as following
((DerivedClass)x).derivedClassMethod();

But it may throw ClassCastException in case x doesn't hold an instance of DerivedClass at that point.

So before casting it to DerivedClass we may like to make sure that it is an instance of DerivedClass and hence won't throw ClassCastException.

So we make a check for it

if(x instanceOf DerivedClass) {
((DerivedClass)x).derivedClassMethod();
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     instanceOf  instanceOf operator  Why we need instanceOf operator  use of instanceOf operator     Asked in 2 Companies      Intermediate        frequent


Related Questions

  In which cases isn't instanceof operator a bad practice?



Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: