Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if number fits primitive type in java?

Tags:

java

integer


I need do to some input validation but run into a question and I do not seem to find an answer (even with Google). The problem is simple: I have 2 positive integers on the input, and I need to check if their product fits int type in Java.
One of my attempts was to compare product with Integer.MAX_VALUE, but it seems if the product is too big for integer, value becomes negative. I wanted to reason that product is too big by change in sign, but it seems if the product is "way too big" it will become positive again.
Could someone advise me how to detect if number becomes too big?
Many thanks in advance!

like image 746
Sergei G Avatar asked Jan 27 '26 20:01

Sergei G


1 Answers

If you are doing a UI, you are presumably in no particular hurry. So you could use a BigInteger and then test the product against MAX_VALUE.

like image 156
bmargulies Avatar answered Jan 29 '26 09:01

bmargulies



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!