Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java handle integer overflow and underflow?

Tags:

java

i know this is an old question, asked many times. but i am not able to find any satisfactory answer for this, hence asking again. can someone explain what exactly happens in case of integer overflow and underflow? i have heard about some 'lower order bytes' which handle this, can someone explain what is that?

thanks!

like image 695
Bhushan Avatar asked Dec 04 '22 09:12

Bhushan


2 Answers

You could imagine that when you have only 2 places you are counting (so adding 1 each time)

 00
 01
 10
 11 
100

But the last one gets cut down to "00" again. So there is your "overflow". You're back at 00. Now depending on what the bits mean, this can mean several things, but most of the time this means you are going from the highest value to the lowest. (11 to 00)

Mark peters adds a good one in the comments: even without overflow you'll have a problem, because the first bit is used as signing, so you'll go from high to low without losing that bit. You could say that the bit is 'separate' from the others

like image 62
Nanne Avatar answered Dec 17 '22 23:12

Nanne


Java loops the number either to the maximum or minimum integer (depending on whether it is overflow or underflow).

So:

System.out.println(Integer.MAX_VALUE + 1 == Integer.MIN_VALUE);
System.out.println(Integer.MIN_VALUE - 1 == Integer.MAX_VALUE);

prints true twice.

like image 37
Jonathan Avatar answered Dec 17 '22 22:12

Jonathan