Sunday 29 March 2020

How Java handles Integer overflows and underflows?

What is Integer Overflow?
Integer Overflow occurs when the result of an arithmetic operation (like Addition, Subtraction, Division, Multiplication etc.,), exceeds the maximum size of the integer type used to store it.

When integer overflows, it goes back to the minimum value and continues from there.

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  int number = Integer.MAX_VALUE;

  for (int i = 0; i < 10; i++) {
   System.out.println(number++);
  }
 }

}

Output
2147483647
-2147483648
-2147483647
-2147483646
-2147483645
-2147483644
-2147483643
-2147483642
-2147483641
-2147483640

What is Integer Underflow?
Integer Underflow occurs when the result of an arithmetic operation (like Addition, Subtraction, Division, Multiplication etc.,), exceeds the minimum size of the integer type used to store it.


When an integer underflows, it goes back to the maximum value and continues from there.

App.java
package com.sample.app;

public class App {

 public static void main(String args[]) {
  int number = Integer.MIN_VALUE;

  for (int i = 0; i < 10; i++) {
   System.out.println(number--);
  }
 }

}

Output

-2147483648
2147483647
2147483646
2147483645
2147483644
2147483643
2147483642
2147483641
2147483640
2147483639


You may like

No comments:

Post a Comment