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.
Java performs all integer arithmetic using int or long operations. A value that is of type byte, short, or char is widened to an int or a long before the arithmetic operation is performed. A value of any integer type can be cast (i.e., converted) to a value of any other integer type.
Arithmetic operations are executed using numeric data. If character string data is specified, arithmetic operations are executed after the character string data is converted to numeric data.
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.
In this java program, we first ask user to enter the number of elements as store it in an integer variable "count". Then we take "count" numbers as input from user using for loop and add them in variable "sum". At the end of for loop, "sum" will contain the total sum of all input numbers.
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:
int c = a + b;
if( c<a) { // assuming a>=0 and b>=0
// overflow happened
}
The second method, is a pre-check, where you basically try to avoid the overflow from happening in the first place. Example:
if( a > Integer.MAX_INTERGER - b ) {
// overflow happened
}
The specific section of the Java Language Specification that deals with these rules is section 4.
If you don't want values to overflow at all, use a BigInteger
or some other arbitrary-precision arithmetic type.
For avoiding overflows in the general case, Guava (which I contribute to) provides methods like IntMath.checkedAdd(int, int)
and LongMath.checkedMultiply(long, long)
, which throw exceptions on overflow. (Some of those are nontrivial to implement yourself, but these are all very exhaustively tested.) You can look at the source to see how they work, but most of them rely on cute bit-twiddling tricks to check for overflow efficiently.
The result of an arithmetic operation on any two primitive integer operands will be at least an int -- even if the operands are bytes and short.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With