简体   繁体   中英

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

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?

You were almost there, it is in 15.18.2 :

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

In Java 7, the relevant sections are JLS 5.6.2 and the respective section for the operator; eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM