Java – can I double or BigDecimal overflow?

Java 8 gave us math Addexact() is an integer, but not a decimal

Can double and BigDecimal overflow? According to double MAX_ Value and how to get biggest BigDecimal value

So why don't we need math Addexact() these types? What is the most maintainable way to check this?

Solution

Double overflow to infinity and - infinity, it will not bypass BigDecimal will not overflow. During, it is only limited by the amount of computer memory See: how to get biggest BigDecimal value

And The only difference between addexact and addexact is that it tries to detect overflow and throws an exception instead of a wrapper This is the source code:

public static int addExact(int x,int y) {
    int r = x + y;
    // HD 2-12 Overflow iff both arguments have the opposite sign of the result
    if (((x ^ r) & (y ^ r)) < 0) {
        throw new ArithmeticException("integer overflow");
    }
    return r;
}

If you want to check whether overflow occurs, in a sense, it is easier to use double precision, because you can simply check double POSITIVE_ Infinity or double NEGATIVE_ INFINITY; In the case of int and long, it is a slightly more complex thing, because it is not always a fixed value, but in the other case, it can be input (for example, infinity 10 = infinity, you may not want to throw an exception in this case)

For all these reasons (we haven't even mentioned Nan), this may be why there is no such addexact method in JDK Of course, you can add your own implementation to the utility class in your own application at any time

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>