How can I check if multiplying two numbers in Java will cause an overflow?

Steve McLeod :

I want to handle the special case where multiplying two numbers together causes an overflow. The code looks something like this:

int a = 20;
long b = 30;

// if a or b are big enough, this result will silently overflow
long c = a * b;

That's a simplified version. In the real program a and b are sourced elsewhere at runtime. What I want to achieve is something like this:

long c;
if (a * b will overflow) {
    c = Long.MAX_VALUE;
} else {
    c = a * b;
}

How do you suggest I best code this?

Update: a and b are always non-negative in my scenario.

bcoughlan :

Java 8 has Math.multiplyExact, Math.addExact etc. for ints and long. These throw an unchecked ArithmeticException on overflow.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I make this F# function not cause a stack overflow

How can I find the multiple of two numbers using Java Modulus

Algorithm for multiplying two numbers

Multiplying two long numbers

How can I check if two Java classes are semantically identical?

How can I check this numbers? c#

How can I verify the sign of product of 3 numbers without multiplying them?

How can format specifiers cause a buffer overflow?

How can I add the values that I got from multiplying two arrays?

How can I check if std::pow will overflow double

How can I print numbers between two numbers that I enter?

How can I calculate the minimum of two numbers?

How can I swap two numbers by address?

When Int overflow cause IOS app crash, how can I remark it

Multiplying two complex numbers in Scheme

Multiplying Two Whole Numbers In Batch

How can I check if two segments intersect?

How can I check that two array are equal or not?

How can I check two conditions in an if statement?

Using having count cause between two numbers, so I can use a range inside the having count clause

how can I skip two numbers and then get the next three numbers?

How to add two float numbers resulting in overflow

How do I check if a string starts with two numbers in Python?

Multiplying numbers that can be float or integer

How can I display a number if it's divisible by two numbers but not a third in java?

I can't find the cause of this Stack Overflow Exception

How can I format int numbers in java?

Enums in java: How can I use numbers

How can I fix overflow error when numbers can be too big?