Then why can't I assign char [] int []?
The first answer is that the Java language specification prohibits this. Key Section 4.10.3. , which defines subtyping rules for array types. Rules mean that a primitive array type is not a subtype of another (different) primitive array type. One consequence of this is the appointment is prohibited.
The second answer (and the reason JLS forbids it) is that it would break the type system if it were allowed. Consider this example:
int[] ints= new int[4]; char[] chars= new char[4]; ints = chars;
Destination is a reference job. This means that ints now points to the array object that was created by new char[4] on the previous line. (This is NOT equivalent to a loop that assigns chars ' values ββto ints elements.)
Now add a method:
public void paranoidIncrement(int[] ints) { for (int i = 0; i < ints.length; i++) { int tmp = int[i]; ints[i] = ints[i] + 1; assert tmp + 1 == ints[i]; } }
and combine it with the previous code:
int[] ints= new int[4]; char[] chars= new char[4]; ints = chars;
So what does that mean? Well paranoidIncrement will consider the argument (which really is char[] ), as if it were int[] . But what happens when we do ints[i] = ints[i] + 1; ? If the cells of the actual array are really char , then the JVM must truncate the values ββso that they match or throw an exception.
If it truncates the value, the assert will fail. And it is so contradictory that it just broke through.
If it throws an exception, then we suddenly have a whole class of new errors (in accordance with the JLS rules) that are currently detected at compile time.
The way Java avoids this malfunction is that you cannot assign char[] int[] .
source share