Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

Java is renowned for its robustness and versatility as a programming language, yet it also presents its fair share of challenges, much like any other language. One prevalent issue that developers frequently confront is the ClassCastException. This exception occurs when attempting to cast an object from one type to another that is not compatible.

In this article, we’ll address the ClassCastException: java.math.BigInteger cannot be cast to java.lang.Integer. This exception is commonly encountered when converting from BigInteger to Integer.

2. Why the ClassCastException Exception Occurs

The BigInteger class in Java facilitates operations involving large integers beyond the range of int and long. Conversely, Integer serves as a wrapper class for the primitive type int. Because these classes serve different purposes and have different internal representations, we cannot directly cast an instance of BigInteger to Integer.

Let’s consider the following code snippet:

Object object = new BigInteger("123");
Integer number = (Integer) obj; // This will throw ClassCastException

In the above example, the ClassCastException exception occurred when attempting to cast a BigInteger to an Integer. It’s crucial to note the importance of verifying the object’s type at runtime before casting to avoid unexpected type conversions and prevent such runtime exceptions.

In the next chapter, we’ll discuss the best practices for avoiding such exceptions.

3. How to Avoid BigInteger to Integer Casting Issues

To avoid the ClassCastException exception, we need to use the right methods and check types for conversions. When working with BigInteger values, we can use the methods provided by the BigInteger class, such as intValue(), to convert the value to an int.

However, we should always check the type of the object before casting it. Additionally, we need to be aware of the potential risk of overflow if the BigInteger value exceeds the range of int (i.e., -2^31 to 2^31-1). If the value is too large, it will wrap around and produce an incorrect result. To mitigate this, we should check if the BigInteger value fits within the int range before converting.

For example, if we have an object that might be a BigInteger or an Integer, we use this method that demonstrates this approach:

int convertIntegerToInt(Object obj) {
    if (obj instanceof BigInteger) {
        BigInteger bigInt = (BigInteger) obj;
        if (bigInt.bitLength() <= 31) {
            return bigInt.intValue();
        } else {
            throw new IllegalArgumentException("BigInteger value is too large to fit in an int");
        }
    } else if (obj instanceof Integer) {
        return (Integer) obj;
    } else {
        throw new IllegalArgumentException("Unsupported type: " + obj.getClass().getName());
    }
}

In the convertToInt() method, we first check the object’s type to determine if it is an instance of BigInteger using the instanceof operator. If it meets this condition, we then cast it to BigInteger. Following this, the method verifies whether its bit length falls within the range that an int can represent (i.e., 31 bits or less).

If this condition is fulfilled, we convert the value to an int using intValue(). On the other hand, if the bit length exceeds the acceptable range, we throw an IllegalArgumentException exception.

If the object is already an Integer, we directly cast it to an Integer and print its value. However, if the object’s type does not match either BigInteger or Integer, we throw an IllegalArgumentException.

This comprehensive approach ensures safe conversion and prevents the ClassCastException by explicitly handling type compatibility.

4. Conclusion

We often encounter the ClassCastException in Java, particularly when trying to cast java.math.BigInteger to java.lang.Integer. To resolve this issue, we need to use appropriate conversion methods provided by the classes, conduct thorough type checks before casting, and potentially restructure our code to mitigate such type mismatches.

By understanding the underlying cause and implementing these solutions, we can proficiently manage and prevent this exception in our Java applications

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

2 Comments
Oldest
Newest