Primitive cast and assignments in Java

前端 未结 3 1796
终归单人心
终归单人心 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:44

    The only thing I can guess is that the compiler equates this expression to the following:

    Yes it does. As long as the right side expression is made of constants (which fit into the required primitive type -- see @Jason's answer for what the JLS says about this exactly), you can do that. This will not compile because 128 is out of range:

    byte a = 128;
    

    Note that if you transform your first code snippet like this:

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

    it compiles! As your two bytes are final and their expressions are constants, this time, the compiler can determine that the result will fit into a byte when it is first initialized.

    This, however, will not compile:

    final byte a = 127; // Byte.MAX_VALUE
    final byte b = 1;
    byte c = a + b // Nope...
    

    The compiler will error out with a "possible loss of precision".

提交回复
热议问题