type casting of byte and int

后端 未结 8 1124
-上瘾入骨i
-上瘾入骨i 2021-01-27 16:27

I\'d a code snippet:

class AutoTypeCast{
    public static void main(String...args){
        int x=10;
        byte b=20;//no compilation error
        byte c=x;         


        
8条回答
  •  無奈伤痛
    2021-01-27 16:55

    In this case x is initialized to 10, so there will be no data loss in the conversion from a 32-bit int to an 8-bit byte. But in general, when converting from int to byte, there can be data loss, so the rules of the Java language forbid assigning int values to a byte without a cast. This rule is designed to make it more difficult to write buggy code. By inserting the (byte) cast, you are effectively telling the compiler: "Yes, I have thought about the possibility of data loss, and it is not a problem here (or, that's actually what I want)."

提交回复
热议问题