data type of results of java arithmetic calculation

我与影子孤独终老i 提交于 2020-04-07 02:54:25

问题


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,

  1. int + int = int

  2. 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.


回答1:


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
}



回答2:


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.




回答3:


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.




回答4:


Answer to question A:

The type of operand with the "larger type"

Double is the "largest" type

Note: char and boolean cannot be used w/ arithmetic operator

Source: https://www.geeksforgeeks.org/type-conversion-java-examples/



来源:https://stackoverflow.com/questions/9981950/data-type-of-results-of-java-arithmetic-calculation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!