How does Java handle integer overflows and underflows ?
Answer :
- Overflows: Once it reached to its maximum value when adding value, It goes back to minimum value and continues from there.
- Underflow: Once it reached to its minimum value when subtract value from it, It will go back to the maximum value and continues from there
Please see example below:
public class UnderflowOverflowTest { public static void main(String[] args) { int i = Integer.MAX_VALUE; System.out.println("int max value: " + i); System.out.println("Add 1 to int max value"); System.out.println("int max value will " + "overflow: " + (i + 1) + "\n"); int j = Integer.MIN_VALUE; System.out.println("int min value: " + j); System.out.println("Subtract 1 to int min value"); System.out.println("int min value will " + "underflow: " + (j - 1)); } }
Output: