Java ProgramsExceptionsClassCastException

ClassCastException in Java

beginner·  Exceptions  ·  Error Handling

Problem

A ClassCastException is thrown when code casts an object reference to a type it doesn't actually belong to, discovered only at runtime since the compiler can't always verify it in advance.

Cast an Object reference that actually holds a String to an incompatible type, and handle the resulting exception.

Input
Object obj = "hello"; Integer number = (Integer) obj;
Output
Error: Cannot cast a String to Integer

Java Program

Java
public class ClassCastExceptionDemo { public static void main(String[] args) { Object obj = "hello"; try { Integer number = (Integer) obj; // obj is really a String, not an Integer System.out.println("Number: " + number); } catch (ClassCastException e) { System.out.println("Error: Cannot cast a String to Integer"); } } }

Output

Error: Cannot cast a String to Integer

Core Logic

Wrapping the risky cast in try-catch lets a mismatched type be caught and reported instead of crashing the program.

How It Works
  1. 1Object obj = "hello"; holds a reference typed as Object, but the actual object underneath is a String.
  2. 2(Integer) obj asks the JVM to treat that same object as an Integer instead.
  3. 3Since the object is genuinely a String, not an Integer, the cast fails at runtime rather than compile time.
  4. 4The catch (ClassCastException e) block catches it and prints a message instead of letting the program crash.
Casting the String-holding obj to Integer throws immediately, caught and printed as "Error: Cannot cast a String to Integer".
💡

Key Point: The compiler allows this cast to compile because obj's declared type is Object, which could hold anything — only at runtime does the JVM check the object's actual type and reject the mismatch.

Key Concepts

try / catchtype castingClassCastException

Related Programs