Weird java behavior with casts to primitive types

后端 未结 3 1838
不知归路
不知归路 2020-11-27 05:39

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

long i = (byte) + (cha         


        
相关标签:
3条回答
  • 2020-11-27 05:56

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

    0 讨论(0)
  • 2020-11-27 06:05

    Unary operators and casting :)

    +1 is legal

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

    Sneaky! Made me think.

    0 讨论(0)
  • 2020-11-27 06:06

    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.

    0 讨论(0)
提交回复
热议问题