Java: why do I receive the error message “Type mismatch: cannot convert int to byte”

后端 未结 4 1828
醉话见心
醉话见心 2020-11-29 11:11

If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error \"Type mismatch: cannot convert int to short\" (o

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 11:53

    I think, the matter is, that the JVM supports only two types of stack values: word sized and double word sized.

    Then they probably decided that they would need only one operation that works on word sized integers on the stack. So there's only iadd, imul and so on at bytecode level (and no operators for bytes and shorts).

    So you get an int value as the result of these operations which Java can't safely convert back to the smaller byte and short data types. So they force you to cast to narrow the value back down to byte/short.

    But in the end you are right: This behaviour is not consistent to the behaviour of ints, for example. You can without problem add two ints and get no error if the result overflows.

提交回复
热议问题