Java int type overflow

Question

What is the output of the following code?



public class Main {
  public static void main(String[] args) {
    int value = 2147483647 + 1;
    System.out.println(value);/*from   www.ja va  2  s .  c o  m*/

    value = -2147483648 - 1; 
    System.out.println(value);
  }
}


-2147483648
2147483647

Note

Numbers are stored with a limited numbers of digits.

When a variable is assigned a value that is too large in size to be stored, it causes overflow.

For example, the following statement causes overflow.

The largest value that can be stored in a variable of the int type is 2147483647.

2147483648 will be too large for an int value.

int value = 2147483647 + 1; 
// value will actually be -2147483648 

The smallest value that can be stored in a variable of the int type is -2147483648.

-2147483649 is too large in size to be stored in an int variable.

int value = -2147483648 - 1; 
// value will actually be 2147483647 

Java does not report warnings or errors on overflow.

Question

What is the output of the following code?

public class Main {
  public static void main(String[] args) {
    int x = 80000000; 

    while (x > 0) 
      x++; //from  ww w .  jav  a  2  s.  c om

     System.out.println("x is " + x); 

  }
}


x is -2147483648

Note

-2147483648 is the result by adding one to Integer.MAX_VALUE.

public class Main {
  public static void main(String[] args) {

    System.out.println(Integer.MAX_VALUE);
    System.out.println(Integer.MAX_VALUE + 1);

  }/*  w  w  w . java 2  s  .  co m*/
}



PreviousNext

Related