In java, I know the data type of the result of an arithmetic calculation depends on the data types of the numbers involved in the calculation.
For example,
-
int + int = int
-
long/double=double
a. But I can’t find any references which can give me all these rules. Could someone help me?
b. How to avoid over flow in arithmetic calculation? For example, the results of 2 long may not fit into a long anymore…
Thanks a lot.
a. These rules are called numeric promotion rules and are specified in Java Language Specification, §5.6.2 (currently).
b. There are two generally accepted method for dealing with overflows.
The first method, a post-check, where you do an operation, say addition and then check that the result is greater than either of the operands. For example:
The second method, is a pre-check, where you basically try to avoid the overflow from happening in the first place. Example: