next up previous
Next: Combined assignment operators Up: Unit 04 Previous: Integer expressions

Numeric overflow

The set of values that can be represented with a primitive type is limited to a specific interval (e.g, [-231,231-1] for the type int). By applying arithmetic operators to values of a given data type, one could obtain a result that falls outside of this interval, and hence cannot be represented with the same primitive data type. Such a situation is called overflow.

Example:

int x = 2147483647;    // maximum value that can be represented as an int
int y = x + 1;         // operation that causes overflow, since the result
                       // 2147483648 cannot be represented as an int
System.out.println(y); // prints -2147483648 instead of 2147483648
                       // (which is the number we would expect)

Note that, by adding 1 to the biggest number that can be represented as an int, we have an overflow, and the result is the smallest number that can be represented as an int. Informally, it is as if we were ``cycling'' around the representation.


next up previous
Next: Combined assignment operators Up: Unit 04 Previous: Integer expressions