Java – why are array assignments incompatible, even if their data type is?
byte b =10;
byte b =10; int a = b; // Primitive data type widening // Works perfectly fine
The above code does not give any errors / warnings But why doesn't the same apply to the code mentioned below?
byte[] b = new byte[10]; int[] i1 = b; //Cannot convert from byte[] to int[] int[] i2 = new byte[10]; //Cannot convert from byte[] to int[]
My question is, because int can save any and all byte values, why is this not the case of arrays?
They are all holding the address If this is possible for the ref variable, then this will be upward
Solution
The language specification defines sec 4.10 Subtypes between array types in 3:
The final bullet ("if P is the base type...") indicates that the language does not define any relationship between arrays of different primitive types The only valid jobs are:
byte[] bs = new byte[10]; byte[] bs2 = bs; Object obj = bs; Cloneable cl = bs; Serializable ser = bs;
This does not explain why; You must ask the language designer However, a simple example like ERAN illustrates why the approach proposed by OP is unsafe
Note the first line – it allows assignment
Object[] obj = new String[10]; obj[0] = new Object(); // ArrayStoreException!
It's a design error: arrays are covariant, making them not type safe This is one reason for a strong preference for generics to arrays, because generics are invariant and therefore prevent such assignments