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

后端 未结 4 1829
醉话见心
醉话见心 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 12:01

    The Java language always promotes arguments of arithmetic operators to int, long, float or double. So take the expression:

    a + b
    

    where a and b are of type byte. This is shorthand for:

    (int)a + (int)b
    

    This expression is of type int. It clearly makes sense to give an error when assigning an int value to a byte variable.

    Why would the language be defined in this way? Suppose a was 60 and b was 70, then a+b is -126 - integer overflow. As part of a more complicated expression that was expected to result in an int, this may become a difficult bug. Restrict use of byte and short to array storage, constants for file formats/network protocols and puzzlers.

    There is an interesting recording from JavaPolis 2007. James Gosling is giving an example about how complicated unsigned arithmetic is (and why it isn't in Java). Josh Bloch points out that his example gives the wrong example under normal signed arithmetic too. For understandable arithmetic, we need arbitrary precision.

提交回复
热议问题