Java Data Type How to - Overflow Int by adding to the Integer.MAX_VALUE








Question

We would like to know how to overflow Int by adding to the Integer.MAX_VALUE.

Answer

public class Main {
  public static void main(String[] unused) {
    do_shorts();//w  w w .  j a v a  2  s  .co m
    do_ints();
  }
  protected static void do_shorts() {
    short i = Short.MAX_VALUE;
    System.out.println("i=" + i++);
    System.out.println("i=" + i++);
    System.out.println("i=" + i++);
  }
  protected static void do_ints() {
    int i = Integer.MAX_VALUE;
    System.out.println("i=" + i++);
    System.out.println("i=" + i++);
    System.out.println("i=" + i++);
  }
}

The code above generates the following result.