user12208242
user12208242

Reputation: 335

Does numeric promotion use narrowing conversion?

I always thought that numeric conversion uses widening conversion and is as simple as just following some priorities like:

If the operands are of type double, everything is converted to double. Next priority being float, then long and then int.

But then I stumbled upon this new JLS which says

If any expression is of type int and is not a constant expression (§15.29), then the promoted type is int, and other expressions that are not of type int undergo widening primitive conversion to int.

Otherwise, if any expression is of type short, and every other expression is either of type short or of type byte or a constant expression of type int with a value that is representable in the type short, then the promoted type is short, and the byte expressions undergo widening primitive conversion to short, and the int expressions undergo narrowing primitive conversion to short.

Otherwise, if any expression is of type byte, and every other expression is either of type byte or a constant expression of type int with a value that is representable in the type byte, then the promoted type is byte, and the int expressions undergo narrowing primitive conversion to byte.

Otherwise, if any expression is of type char, and every other expression is either of type char or a constant expression of type int with a value that is representable in the type char, then the promoted type is char, and the int expressions undergo narrowing primitive conversion to char.

Otherwise, the promoted type is int, and all the expressions that are not of type int undergo widening primitive conversion to int.

Can you tell me what does this mean? When does numeric promotion use narrowing conversion? I am sorry if this is a dope question but I'm a non-English speaker and this is getting too english for me to understand.

Upvotes: 1

Views: 102

Answers (1)

JustAnotherDeveloper
JustAnotherDeveloper

Reputation: 2256

If two values have different data types, Java will automatically promote one of the values to the larger of the two data types.

If one of the values is integral and the other is floating-point, Java will automatically promote the integral value to the floating-point value’s data type.

Smaller data types, namely byte, short, and char, are first promoted to int any time they’re used with a Java binary arithmetic operator, even if neither of the operands is int.

After all promotion has occurred and the operands have the same data type, the resulting value will have the same data type as its promoted operands.

Narrowing conversion only affects, as per what you posted, numeric expressions of type int that are both a constant and representable in the narrower type.

Upvotes: 1

Related Questions