Why are array assignments incompatible, even though their data types are?

前端 未结 2 1400
时光说笑
时光说笑 2021-01-20 18:41
byte b =10;   
int a = b;   // Primitive data type widening
             // Works perfectly fine

the above code will give no error/warnings. But wh

2条回答
  •  粉色の甜心
    2021-01-20 18:59

    The array created by new byte[10] can contain 10 byte values. If you were able to assign it to a variable of type int[], the compiler would assume (mistakenly) that your array of bytes can contain 10 int values.

    Consider the following code, which is invalid:

    byte[] b = new byte[10];
    b[0] = 10000; // too large for byte
    

    and the following code, which is valid:

    int[] i2 = new int[10];
    i2[0] = 10000;
    

    If int[] i2 = new byte[10]; was valid, the compiler would have allowed you to store an int in a variable of type byte.

提交回复
热议问题