使用强制转换为基本类型的奇怪java行为

时间:2022-02-16 16:27:23

This was probably asked somewhere but I couldn't find it. Could someone clarify why this code compiles and prints out 1?

这可能是在某个地方被问到但我找不到它。有人可以澄清为什么这个代码编译并打印1?

long i = (byte) + (char) - (int) + (long) - 1;
System.out.println(i);

3 个解决方案

#1


42  

It's being parsed as this:

它被解析为:

long i = (byte)( +(char)( -(int)( +(long)(-1) ) ) );

where all the + and - operators are unary + or -.

所有+和 - 运算符都是一元+或 - 。

In which case, the 1 gets negated twice, so it prints out as a 1.

在这种情况下,1被否定两次,因此它打印为1。

#2


5  

Because both '+' and '-' are unary operators, and the casts are working on the operands of those unaries. The rest is math.

因为'+'和' - '都是一元运算符,而演员正在研究那些一元的操作数。剩下的就是数学。

#3


5  

Unary operators and casting :)

一元运算符和铸造:)

+1 is legal

+1是合法的

(byte) + 1 is casting +1 to a byte.

(byte)+ 1将+1转换为一个字节。

Sneaky! Made me think.

偷偷摸摸的!让我思考。

#1


42  

It's being parsed as this:

它被解析为:

long i = (byte)( +(char)( -(int)( +(long)(-1) ) ) );

where all the + and - operators are unary + or -.

所有+和 - 运算符都是一元+或 - 。

In which case, the 1 gets negated twice, so it prints out as a 1.

在这种情况下,1被否定两次,因此它打印为1。

#2


5  

Because both '+' and '-' are unary operators, and the casts are working on the operands of those unaries. The rest is math.

因为'+'和' - '都是一元运算符,而演员正在研究那些一元的操作数。剩下的就是数学。

#3


5  

Unary operators and casting :)

一元运算符和铸造:)

+1 is legal

+1是合法的

(byte) + 1 is casting +1 to a byte.

(byte)+ 1将+1转换为一个字节。

Sneaky! Made me think.

偷偷摸摸的!让我思考。