Java – code object o = true? New integer (0): new long (1) returns long with a value of 0 Why?

See the English answer > java conditional operator?: Result type5

Object obj = true ? new Integer(0) : new Long(1);
System.out.println(obj.getClass() + "\nvalue = " + obj);

The result is:

class java.lang.Long
value = 0

Substitute:

class java.lang.Integer
value = 0

Can someone clarify why we have such a function in Java? It's strange to me. Do you have any examples to use?

Update: This is a bytecode. We can see what's there

NEW java/lang/Integer
DUP
LDC "0"
INVOKESPECIAL java/lang/Integer.<init> (Ljava/lang/String;)V
INVOKEVIRTUAL java/lang/Integer.intValue ()I
I2L
INVOKESTATIC java/lang/Long.valueOf (J)Ljava/lang/Long;
ASTORE 1

Solution

What happens here is the result

>Binary number promotion enables your integer and long types to be used for a long time as common types applied to conditional operator expressions > unpack these wrapper Objects > and then box the result value of the conditional expression

The second and third operands of the conditional operator must end up with the same type, which is the result type of the expression Integers and lengths are certainly not of the same type

However, as described in JLS § 15.25, the compiler will apply binary numeric promotion when determining the possible common types applied to expressions There is a convenient table 15.25-d in this section, which tells us that when the type of the second operand is integer and the type of the third operand is long, the compiler will perform binary digit upgrade on integer long The binary digit extension of integers has a long output Therefore, the result of conditional operator expression is very long

Because the result type of the expression is very long, integer or long will have to be unboxed (and then projected in the case of integer)

Finally, you assign it to an object, which forces boxing and wraps it in long So, you end up with a long that contains the value 0. 0 that matches the output

Therefore, if we ignore the fact that the compiler will optimize the following half because it handles a constant expression, the code will end up like this due to the reality in the code (I have used the following flag):

Object obj = Long.valueOf(flag ? (long)(new Integer(0)).intValue() : (new Long(1)).longValue());
System.out.println(obj.getClass() + "\nvalue = " + obj);

>(long)(new Integer(0)). Intvalue() means unpacking an integer and converting it to long, so it matches the expression result type. > (New Long(1)). Longvalue () means to split long, so it matches the expression result type. > And long Valueof stands for the last boxing

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>