Java JLS defines promotion of primitive wrapper types?

I am a little puzzled by the release of this program:

public class xx { public static void main(String[] args) throws Exception { Number x = false ? new Long(123) : new Integer(456); System.out.println(x + " isa " + x.getClass().getName()); } } 

Here it outputs:

 456 isa java.lang.Long 

It seems that the compiler "pushes" an object of type Integer to Long , just as it usually pushes primitive values. I have never heard of the promotion of objects, and this behavior seems very unexpected.

My question is: is this really the correct behavior according to JLS? If so, I would like to see a link, if possible.

Or is this some kind of autoboxing-off-wild compiler error?

I use:

 java version "1.8.0_60" Java(TM) SE Runtime Environment (build 1.8.0_60-b27) Java HotSpot(TM) 64-Bit Server VM (build 25.60-b23, mixed mode) 
+5
source share
2 answers

This is actually binary numeric promotion ( JLS, section 5.6.2 ).

When an operator applies binary numeric promotion to a pair of operands, each of which must indicate a value that can be converted to a numeric type, the following rules apply to:

  • If any operand has a reference type, it undergoes unpacking of the transformation (section 5.1.8).

  • The primitive conversion extension (§5.1.2) is used to convert one or both operands, as specified in the following rules:

    • If one of the operands is of type double, the other is converted to double.

    • Otherwise, if either operand is of type float, the other is converted to float.

    • Otherwise, if either operand is of type long, the other is converted to long.

    • Otherwise, both operands are converted to int type.

For operands of certain operators, binary numeric promotion is performed:

...

  • In some cases, the conditional operator ?: (§15.25)

So, the operands are unpacked, and the 456 expands to 456L .

In addition, the specific case of Long and Integer explicitly considered by the JLS section for the conditional statement, JLS Section 15.25, Table 15.25-C .

BNP (Long, Integer)

where "bnp" means binary numeric promotion. Therefore, the expression of the conditional operator is of type Long , which binds to Long , which must be bound to Number .

+4
source

JLS defines expression type a ? b : c a ? b : c in the case of b and c are Long and Integer respectively in this table .

The type of expression is really long, and in fact there is binary digital advertising (bnp) from Integer to Long.

The following is the rule here :

The type of numerical conditional expression is defined as follows:

[...]

Otherwise, binary numeric promotion (§5.6.2) is used for operand types, and the conditional expression type is the advanced type of the second and third operands.

+3
source

Source: https://habr.com/ru/post/1241083/


All Articles