Why is “int i = 2147483647 + 1;” OK, but “byte b = 127 + 1;” is not compilable?

后端 未结 4 1015
囚心锁ツ
囚心锁ツ 2020-12-12 18:45

Why is int i = 2147483647 + 1; OK, but byte b = 127 + 1; is not compilable?

4条回答
  •  借酒劲吻你
    2020-12-12 19:09

    The literal 127 denotes a value of type int. So does the literal 1. The sum of these two is the integer 128. The problem, in the second case, is that you are assigning this to a variable of type byte. It has nothing to do with the actual value of the expressions. It has to do with Java not supporting coercions (*). You have to add a typecast

    byte b = (byte)(127 + 1);
    

    and then it compiles.

    (*) at least not of the kind String-to-integer, float-to-Time, ... Java does support coercions if they are, in a sense, non-loss (Java calls this "widening").

    And no, the word "coercion" did not need correcting. It was chosen very deliberately and correctly at that. From the closest source to hand (Wikipedia) : "In most languages, the word coercion is used to denote an implicit conversion, either during compilation or during run time." and "In computer science, type conversion, typecasting, and coercion are different ways of, implicitly or explicitly, changing an entity of one data type into another.".

提交回复
热议问题