type casting of byte and int

后端 未结 8 1175
-上瘾入骨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

    When the compiler looks at the line

    byte b=20;
    

    it knows it's looking for a byte after b=. When it finds a constant numeric value it knows at compile time that it will definitely be in the range of byte so it will automatically cast it.

    When is sees the line

    byte c=x;
    

    it's once again looking for a byte after c= but instead of finding a numeric constant, finds a variable that already has a defined type and, at compile time, can't be sure that it will be in the range of byte so you get an error.

提交回复
热议问题