
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is a ClassCastException and when it will be thrown in Java?
The java.lang.ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type.
When will be ClassCastException is thrown
- When we try to cast an object of Parent class to its Child class type, this exception will be thrown.
- When we try to cast an object of one class into another class type that has not extended the other class or they don't have any relationship between them.
Example
class ParentTest { String parentName; ParentTest(String n1){ parentName = n1; } public void display() { System.out.println(parentName); } } class ChildTest extends ParentTest { String childName; ChildTest(String n2) { super(n2); childName = n2; } public void display() { System.out.println(childName); } } public class Test { public static void main(String args[]) { ChildTest ct1 = new ChildTest("Jai"); ParentTest pt1 = new ParentTest("Adithya"); pt1 = ct1; pt1.display(); ParentTest pt2 = new ParentTest("Sai"); ChildTest ct2 = (ChildTest)pt2; } }
Output
Jai Exception in thread "main" java.lang.ClassCastException: ParentTest cannot be cast to ChildTest at Test.main(Test.java:30)
- Related Questions & Answers
- When will be an IllegalStateException (unchecked) thrown in Java?
- When does a NullPointerException get thrown in java?
- When do IllegalStateException and IllegalArgumentException get thrown? in java?
- What is no-confidence motion? When can it be held?
- What is training? When and why it is needed?
- When will 5G services be launched in India?
- What is a psychometric test? When is it conducted?
- What is Scanner class in Java? when was it introduced?
- What is Babel, and how will it help you write JavaScript?
- How can an exception be thrown manually by a programmer in java?
- When is plt.Show() required to show a plot and when is it not?
- What will happen when { } is converted to String in JavaScript?
- What is a lunar eclipse? When does it occur?
- When will be an object eligible for garbage collection?
- What is a smart pointer and when should I use it in C++?
Advertisements