We are going to describe class cast exception in java. The class cast exception is a converting one data type into another data type. A Class cast exception is a thrown by java. In this example instances to handle class cast exception in a programs..Exceptions are the way in Java to indicate to a calling method that an unnatural condition has occurred.
Class Cast Exception Example in java
We are going to describe class cast exception in java. The class cast exception is a converting one data type into another data type. A Class cast exception is a thrown by java. In this example instances to handle class cast exception in a programs..Exceptions are the way in Java to indicate to a calling method that an unnatural condition has occurred.
In this example we have to convert one data type into to another data type by using castiing.
Vector vector = new Vector():-Creates a new vector.
Object obj = vector.add( a ):-Adds an integer type to the vector and stores in an object
To avoid this exception we have to add Integer a = new Integer((String)obj)
instead of String a = (String)obj.
Example
import java.util.Vector; public class ClassCast { public static void main(String[] args) { Vector vector = new Vector(); int a = 10; Object obj = vector.add(a); try { String b = (String)obj; vector.add(b); } catch (ClassCastException e) { System.out.println("Class cast exception: " + obj.getClass().getName()); e.printStackTrace(); } } }
output