Core Java - Interview Questions and Answers for 'Runtime exceptions' | Search Interview Question -

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


Core Java - Interview Questions and Answers for 'Runtime exceptions' - 1 question(s) found - Order By Newest

 Q1. In which cases isn't instanceof operator a bad practice?Core Java
Ans. To avoid ClassCastException.

Though the following code will compile fine but will result in ClassCastException during runtime.

Fruit fruit = new Apple();
Banana banana = Banana(fruit); // ClassCastException

This code will not give compile time error as Banana and Fruit are related as Banana either extends or implement Fruit, So downcasting is acceptable. With this code we assume that the Fruit handler will have the Apple object at that point, violating which the code will throw the exception.

This exception can be avoided by following code.

Fruit fruit = new Apple();
if(fruit instanceOf Banana){
Banana banana = Banana(fruit); // ClassCastException

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

   Like         Discuss         Correct / Improve     java   instanceof   classcastexception   runtime exceptions  instanceOf operator

Try 2 Question(s) Test

Related Questions

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: