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

后端 未结 4 1802
醉话见心
醉话见心 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:07

    The answer to your follow-up question is here:

    operands of type byte and short are automatically promoted to int before being handed to the operators

    So, in your example, a and b are both converted to an int before being handed to the + operator. The result of adding two ints together is also an int. Trying to then assign that int to a byte value causes the error because there is a potential loss of precision. By explicitly casting the result you are telling the compiler "I know what I am doing".

提交回复
热议问题