Consequences Of Integer OverFlow/Underflow
The following can be the consequences of the integer overflow, underflow, or wraparound:
- The program will produce inaccurate results from mathematical computations because of integer overflow or underflow
- If a variable is used as a loop control variable with a condition to stop when its value is greater than a fixed value, this condition might never be reached because of integer overflow, resulting in an infinite loop.
- If a variable is used to decide the memory to be allocated to a buffer, a negative value resulting from integer overflow can lead to a system crash.
How to Avoid Integer Overflow/Underflow
The best way to avoid integer overflow or underflow errors is by making sure that the variable used for storing integer values is allocated the right amount of memory. For Java, the following types are available for storing integers:
- Type byte: 8 bits for storing the range -127-128
- Type short: 16 bits for storing the range -32,768 to 32,767
- Type int: 4 bytes for storing the range -2,147,483,648 to 2,147,483,647
- Type long: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
- Type char: This is used to store characters, but whole numbers from 0 to 65535 can also be stored in this type
Some programming languages allow special data structures to detect integer overflow or underflow. For example, Java 8 includes Math.addExact()
. This method throws an ArithmeticException
when wraparounds occur in integer arithmetic and give programmers a chance to catch such exceptions and take action.
