Integer value considerations.

exercise No. 105

Q:

Consider the following piece of code:

int a = ..., b = ...;
...// statements being omitted
int sum = a + b;

Which representation related problem may arise here? May you supply a solution?

A:

The sum of a and b may either exceed java.lang.Integer.MAX_VALUE or in turn may be less than java.lang.Integer.MIN_VALUE. To avoid this type of overflow error our variable sum may be declared of type long:

int a = ..., b = ...;
...// statements being omitted
long sum = a + b;

Unfortunately this does not (yet) help at all: Since both operands a and b are of type int the expression a + b is also of type int and will be evaluated as such. To circumvent this problem we have to cast at least one operand to type long prior to computing the sum. This works since the cast operator (long) does have higher priority than the + operator

int a = ..., b = ...;
...// statements being omitted
long sum = (long)a + b;