September 2019
Intermediate to advanced
816 pages
18h 47m
English
Let's dive into the solution by starting with the + operator, as in the following example:
int x = 2;int y = 7;int z = x + y; // 9
This is a very simple approach and works fine for most of the computations that involve int, long, float, and double.
Now, let's apply this operator on the following two large numbers (sum 2,147,483,647 with itself):
int x = Integer.MAX_VALUE;int y = Integer.MAX_VALUE;int z = x + y; // -2
This time, z will be equal to -2, which is not the expected result, that is, 4,294,967,294. Changing only the z type from int to long will not help. However, changing the types of x and y from int to long as well will help:
long x = Integer.MAX_VALUE;long y = Integer.MAX_VALUE; ...