type casting of byte and int

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

    Because x is an int and has a wider range as byte. That is why there may be data loss is you assign it to byte.

    20 is a constant and while compile time garanteed to be in the range of byte.

    0 讨论(0)
  • 2021-01-27 17:15

    Up-casting is automatic where as down-casting or narrowing (byte c=x;) should be explicit as it might cause loss of precision which a programmer should be aware of explicitly. To correct it you need to put an explicit cast byte c=(byte)x;

    0 讨论(0)
提交回复
热议问题