ClassCastException Java Origin: Application & API Last updated 12 Oct 2026

java.lang.ClassCastException: class A cannot be cast to class B

An object was cast to a type it isn’t.

Exact message you may see cannot be cast to class
Seen on: Java

Meaning

Raw collections, deserialized data (Integer vs Long), and objects from different class loaders (same class name, different loader) commonly cause it.

Common causes

  • Wrong assumption about runtime type
  • Raw/untyped collections
  • JSON numbers deserialized as Integer vs Long
  • Class loader duplicates in app servers

⚡ Quick fix

  1. Use generics instead of raw types
  2. Check with instanceof / pattern matching
  3. Convert numbers via Number.longValue()

Detailed fix by platform

Java

  1. if (value instanceof Number n) { long id = n.longValue(); }

How to diagnose

  1. Types — Both classes in the message
  2. Loaders — Same class name in two loaders?

🔧 Still not fixed?

Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:

Where this error sits

Origin: Application & API. Errors that are often confused with or caused by this one (click to open):

Array to string conversion — Warning: Array to string conversion (PHP)Array to string conve…Cannot convert value of type — Swift: Cannot convert value of type 'X' to expected argument type 'Y' (iOS)Cannot convert value …Cannot use object as array — Fatal error: Uncaught Error: Cannot use object of type stdClass as array (PHP)Cannot use object as …E0308 — Rust: error[E0308]: mismatched types — expected `X`, found `Y` (Rust)E0308ERR_INVALID_ARG_TYPE — TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received undefined (Node.js)ERR_INVALID_ARG_TYPEImplicit float to int — Deprecated: Implicit conversion from float 2.5 to int loses precision (PHP)Implicit float to intStream closed — java.io.IOException: Stream closed (Java)Stream closedStringIndexOutOfBoundsException — java.lang.StringIndexOutOfBoundsException: begin 0, end 10, length 5 (Java)StringIndexOutOfBound…ClassCast…

Explore the map of this error Full error map →

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.

💬 What worked for others

No tips yet — did something else fix this for you?

Share what worked for you

Tips are checked by an editor before they appear. Links are removed.