type casting of byte and int

后端 未结 8 1036
-上瘾入骨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 17:04

    Because compiler is not able to figure out the value of X at compile time. So it assume that X can contain value which is greater than byte range. If you make variable X as final then it will not give you compile time error.

            final int x=10;
            byte b=20;//no compilation error
            byte c=x;//no compilation error
    

提交回复
热议问题