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

StackOverflow https://stackoverflow.com/questions/16633949

  •  29-05-2022
  •  | 
  •  

Domanda

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?

È stato utile?

Soluzione

You were almost there, it is in 15.18.2:

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top