类型转换为byte和int

Moh*_*sal 0 java

我有一个代码片段:

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

为什么20会自动键入式浇铸byte,而x不是?

jue*_*n d 5

因为x是一个int并且具有更广泛的范围byte.这就是为什么你可能会分配数据丢失的原因byte.

20是一个常数,而编译时间保证在byte.范围内.