Skip to content
Advertisement

java Integer.MAX_VALUE, MIN_VALUE overflow

Ok maybe I am just tired because of this but how can I accomplish this?

int x = Integer.MAX_VALUE+10;

// or perhaps

int x = Integer.MIN_VALUE-20;

I just want the if statement to catch if x is “within range” kinda like this:

if(x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE){ //throw exception}

But the problem is that if the value is as mentioned above, like MAX_VALUE + 10, the value ends up being neither higher than the MAX VALUE nor lower than the MIN_VALUE and the if-conditions aren’t met…

Edit: To clarify what I meant: I don’t want to actually store any values bigger than the max/min value. Imagine this:

A field, you write 10+10 and it says like “Ok, that’s 20” Next up, someone maybe will write 1000000100000 and it will respond with the answer as well but then someone might write something that exceeds the max/min values like, 100000001000000*1000000 or someyhing like that and then the program should be all like “Hold up, that’s way too high! here’s a “0” for you instead”

Advertisement

Answer

This can be solved in 2 ways:

First way:

if(x + 10 <= x){ //Has wrapped arround so throw exception}

Second way (better):

long x = Integer.MAX_VALUE+10L;
Now the conditional works properly

if(x >= Integer.MAX_VALUE){ //throw exception}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement