Primitive cast and assignments in Java

前端 未结 3 1791
终归单人心
终归单人心 2020-12-05 03:50

I understand why the following is wrong:

byte a = 3; 
byte b = 8; 
byte c = a + b;  // compile error

It won\'t compile. Expressions alway

3条回答
  •  一向
    一向 (楼主)
    2020-12-05 04:49

    It is because 3 and 8 are compile time constants.

    Therefore, at the time of compilation happens, compiler can identify that 3 + 8 can fit into a byte variable.

    If you make your a and b to final (constant) variable. a + b will become a compile time constant. Therefore, it will compile without any issue.

        final byte a = 3;
        final byte b = 8;
        byte c = a + b;
    

提交回复
热议问题