Interview Questions and Answers for 'Classcastexception' | Search Interview Question - javasearch.buggybread.com
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 for 'Classcastexception' - 2 question(s) found - Order By Newest

 Q1. When do you get ClassCastException?

or

What is ClassCastException ?
Ans. As we only downcast class in the hierarchy, The ClassCastException is thrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance.

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

   Like         Discuss         Correct / Improve     java   oops   class casting   classcastexception   exception   error     Asked in 4 Companies      intermediate        frequent

Try 2 Question(s) Test


Related Questions

  In which cases isn't instanceof operator a bad practice?
  Invoking start twice on same thread leads to ..


 Q2. 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: