0

After going through this question, i had one another in my mind. Question: Why an integer variable value is set to Integer.MAX_VALUE.

eg.

int x = Integer.MIN_VALUE;
x--;
if (x == Integer.MAX_VALUE) {
    System.out.println("Why....");
}

There must be some reason that is why this behavior implemented explicitly, otherwise throwing an Exception would be a better idea. I could not find/locate this behavior in JLS.

Community
  • 1
  • 1
Gaurav Gupta
  • 4,586
  • 4
  • 39
  • 72

2 Answers2

3

Because of underflow. Computers have worked like this for years, throwing an Exception would be a horrible idea here.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • But throwing an Exception would be a bad idea, what would be side-effects if `IntegerValueUnderFlowException` would be implemented in place of assigning mathematically as well as logically wrong value. – Gaurav Gupta Sep 19 '13 at 12:17
  • @GauravGupta The processor works like this too. Granted, it does set flags indicating that underflow occurred, but it's not an error such as dividing by zero. – Kayaman Sep 19 '13 at 12:32
2

http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.2

"The integer operators do not indicate overflow or underflow in any way."

tazmanos
  • 313
  • 2
  • 9