How can I safely convert long into int in Java?

Asked 2 years ago, Updated 2 years ago, 76 views

What is the best way to avoid data loss when converting from long to int?

public static int safeLongToInt(long l) {
    int i = (int)l;
    if ((long)i != l) {
        throw new IllegalArgumentException(l + " cannot be cast to int without changing its value.");
    }
    return i;
}

This is what I've implemented.

java casting

2022-09-22 22:25

1 Answers

A new method has been added in Java 8.

import static java.lang.Math.toIntExact;

long foo = 10L;
int bar = toIntExact(foo);

If it overflows, throws an error called ArithmeticException. In Java 8, a safe method has been added to these overflows, all ending with exact.


2022-09-22 22:25

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.