Safely casting long to int in Java
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Casting a long to an int in Java is legal syntax, but it is only safe when the value fits in the int range. If it does not, Java silently truncates the high bits, which means you get a wrong number instead of an exception unless you check explicitly.
Understand What a Narrowing Cast Does
long is 64-bit and int is 32-bit. A direct cast throws away information when the long value is outside the int range.
This compiles and runs, but the printed int is not the original number. That silent corruption is the real danger.
Use Math.toIntExact When Overflow Is an Error
The safest built-in option is Math.toIntExact. It returns the converted value if the cast is safe and throws ArithmeticException if it is not.
This is usually the best choice when bad data should fail fast instead of being quietly transformed into a nonsense value.
Use an Explicit Range Check for Custom Handling
Sometimes your business rule is not "throw on overflow." Maybe you want to log, reject the record, or map out-of-range values to a domain-specific response. In that case, do the range check yourself.
This is a good pattern when you want the exception type or message to reflect your own API contract.
Clamp Only When the Business Rule Really Calls for It
Sometimes the desired behavior is to cap values at the nearest valid boundary. That is a business decision, not a generic cast strategy.
This can make sense for UI sliders, scoring caps, or coarse telemetry buckets. It is usually wrong for ids, money, counters, or anything where exactness matters.
Validate Data at the Boundary
Safe casting becomes easier when validation happens as soon as data enters the system. For example, if a JSON payload or JDBC result is expected to fit inside an int, check it there instead of allowing an oversized long to move through several layers first.
That keeps the failure close to the source and makes debugging much simpler.
Common Pitfalls
- Using
(int) someLongand assuming Java will protect you from overflow. - Clamping values when the correct behavior should be rejection or failure.
- Delaying range validation until far downstream, where the source of the bad value is harder to trace.
- Converting ids or counts with silent narrowing and then storing corrupted values.
- Writing your own helper but forgetting to cover both
Integer.MIN_VALUEandInteger.MAX_VALUE.
Summary
- A direct cast from
longtointcan silently corrupt data. - Use
Math.toIntExactwhen out-of-range values should fail immediately. - Use explicit range checks when your application needs custom error handling.
- Clamp only when the product requirement truly calls for lossy conversion.
- Validate numeric bounds early so bad values do not spread through the system.
Related reading
- Save ArrayList to SharedPreferences
- Scala equivalent of Java java.lang.ClassT Object
- Scala Programming for Android
- Scalable spring batch job on kubernetes
- Scan components of different maven modules/JARs in a Spring Boot application
- Scanner is skipping nextLine() after using next() or nextFoo()?
- Scanner vs. BufferedReader
- Scanner vs. StringTokenizer vs. String.Split

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.