Data type of Java arithmetic calculation result
In Java, I know that the data type of arithmetic calculation results depends on the data type of numbers involved in the calculation
> int int = int > long / double = double
One But I can't find any reference that can give me all these rules Can someone help me?
How to avoid overcurrent in Bay arithmetic calculation? For example, 2 long results may no longer be suitable for long
Thank you.
Solution
One These rules are called digital promotion rules and are specified in the Java language specification
There are two generally accepted methods to deal with spills
The first method is to check where you perform operations, such as addition, and then check whether the result is greater than any operand For example:
int c = a + b; if( c<a) { // assuming a>=0 and b>=0 // overflow happened }
The second method is pre - check. You basically try to avoid overflow first Example:
if( a > Integer.MAX_INTERGER - b ) { // overflow happened }