Where does the JLS specify that the result of an addition is int if its operands are of smaller type?

孤者浪人 提交于 2019-12-11 03:43:23

问题


With reference to Why i am getting type mismatch: cannot convert from int to byte, I tried a quick search in the JLS to find where is it mentioned that the result of an addition between byte operands is automatically widened to int.

The best I found was this tutorial, but I didnt' find anything in the JLS.

The Conversions chapter does not mention anything about the addition operator, at least I couldn't find something. The Additive Operators paragraph does not mention automatic widening of byte. It mentions that the type of each of the operands of the binary - operator must be a type that is convertible (§5.1.8) to a primitive numeric type, but nothing about widening. And byte is a numeric data type.

What am I missing?


回答1:


You were almost there, it is in 15.18.2:

Binary numeric promotion is performed on the operands (§5.6.2).




回答2:


In Java 7, the relevant sections are JLS 5.6.2 and the respective section for the operator; e.g. JLS 15.18.2 for the binary additive operators on numbers.

The operator sections say that binary promotion is performed first. Then section 5.6.2 explains that binary promotion for byte, short and char means conversion to int if the other operand is integral.



来源:https://stackoverflow.com/questions/16633949/where-does-the-jls-specify-that-the-result-of-an-addition-is-int-if-its-operands

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