Java ClassCastException
A cast of a non-null object to an incompatible reference type throws ClassCastException. Pattern matching with instanceof can validate imported values before use.
A simple example
ClassCastException
- Start with Text "2" where an integer is required
- Do this Check or cast the type
- Result Type mismatch
Syntax
(Integer) importedFare
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaCheck the type of an imported fare
A transit app imports fares from two ticket machines. One machine sends the word “free” in a field normally filled with a whole number, so the importer needs to flag the record for review.
class Main {
public static void main(String[] args) throws Exception {
Object importedFare = "free";
try {
int fare = (Integer) importedFare;
System.out.println(fare);
} catch (ClassCastException wrongType) {
System.out.println("Review fare type");
}
}
}
Review fare type
The stored object is a String. The JVM rejects the cast before the application can treat the fare as an integer.
Accept a numeric fare without a blind cast
A newer ticket machine exports an integer fare in cents. Before it formats the receipt, the billing service checks the actual type of the imported value.
class Main {
public static void main(String[] args) throws Exception {
Object imported = 250;
if (imported instanceof Integer cents) {
System.out.println(cents + " cents");
}
}
}
250 cents
The pattern variable is available only on the branch where the value is an Integer.
Import a museum headcount
The counter sends the number 36 as an integer object. The import expects an integer value. Flag a text field for review before calculating a total.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
Object field=36;
int count=(Integer)field;
System.out.println("Number accepted");
} catch (ClassCastException problem) {
System.out.println("Review field type");
}
}
}
Number accepted
What to watch for
Casting a String to Integer does not parse its contents. Parse text explicitly if numeric strings are allowed.