Library contents

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

  1. Start with Text "2" where an integer is required
  2. Do this Check or cast the type
  3. Result Type mismatch
A string containing a digit is still a string. Parsing would be a separate operation.

Syntax

Java syntax
(Integer) importedFare
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Check 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.

From the programObject importedFare = "free"
ResultReview fare type
Main.java
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");
        }
    }
}
Output
Review fare type

The stored object is a String. The JVM rejects the cast before the application can treat the fare as an integer.

Advertisements

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.

From the programObject imported = 250
Result250 cents
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        Object imported = 250;
        if (imported instanceof Integer cents) {
            System.out.println(cents + " cents");
        }
    }
}
Output
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.

GivenInteger 36
Worked resultNumber accepted
Code and output in Java
Java source
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");
        }
    }
}
Output
Number accepted

What to watch for

Casting a String to Integer does not parse its contents. Parse text explicitly if numeric strings are allowed.

Documentation for ClassCastException