Java
Programming
Data Types
Type Casting
Code Safety

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.

Browse interview questions

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.

java
1public class NarrowingDemo {
2    public static void main(String[] args) {
3        long value = 3_000_000_000L;
4        int narrowed = (int) value;
5
6        System.out.println("original: " + value);
7        System.out.println("narrowed: " + narrowed);
8    }
9}

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.

java
1public class ExactCastDemo {
2    public static void main(String[] args) {
3        long safe = 42L;
4        long unsafe = 3_000_000_000L;
5
6        System.out.println(Math.toIntExact(safe));
7
8        try {
9            System.out.println(Math.toIntExact(unsafe));
10        } catch (ArithmeticException ex) {
11            System.out.println("Overflow detected: " + ex.getMessage());
12        }
13    }
14}

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.

java
1public final class IntCaster {
2    public static int checkedLongToInt(long value) {
3        if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
4            throw new IllegalArgumentException("Out of int range: " + value);
5        }
6        return (int) value;
7    }
8
9    public static void main(String[] args) {
10        System.out.println(checkedLongToInt(99L));
11    }
12}

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.

java
1public class ClampDemo {
2    public static int clampLongToInt(long value) {
3        if (value < Integer.MIN_VALUE) {
4            return Integer.MIN_VALUE;
5        }
6        if (value > Integer.MAX_VALUE) {
7            return Integer.MAX_VALUE;
8        }
9        return (int) value;
10    }
11}

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.

java
1record UserInput(long retries) {}
2
3public class BoundaryValidation {
4    public static int retriesAsInt(UserInput input) {
5        return Math.toIntExact(input.retries());
6    }
7}

That keeps the failure close to the source and makes debugging much simpler.

Common Pitfalls

  • Using (int) someLong and 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_VALUE and Integer.MAX_VALUE.

Summary

  • A direct cast from long to int can silently corrupt data.
  • Use Math.toIntExact when 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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.