Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert from char[] to int[]

Tags:

java

I can assign char to int as follows.

char c = 'a';
int  a = 0;
     a = c;

Then, why I can't assign a char[] to int[]?

int[] ints= new int[4];
char[] chars= new char[4];
ints = chars;   // Cannot convert from char[] to int[] ?? But why?
like image 374
namalfernandolk Avatar asked Jan 17 '23 16:01

namalfernandolk


2 Answers

The char to int promotion is a special provision for primitive types.

Regarding arrays, the Java Language Specification says this:

If an array variable v has type A[], where A is a reference type, then v can hold a reference to an instance of any array type B[], provided B can be assigned to A. This may result in a run-time exception on a later assignment; see §10.10 for a discussion.

This works only "if A is a reference type." Even though char can be assigned to int, this rule doesn't apply because it doesn't apply to primitive types.

So, without any special provision for assigning incompatible types, the assignment fails.

If it were allowed, you'd introduce the possibility of ArrayStoreException being raised on stores to primitive arrays (just like you currently have with arrays of reference types):

ints[0] = Integer.MAX_VALUE; /* Exception! */

This happens because ints is an alias to a char[] that can't accommodate a 32-bit value. I'm not sure why this is acceptable for reference types, and not for primitives, but it probably has to do with all of the special treatment already required for primitives.

like image 159
erickson Avatar answered Jan 28 '23 12:01

erickson


Not sure I can supply more for you other than the concept of casting from char[] to int[] doesn't exist in the language specification.

At a low level, it probably has to do with iteration through the array itself. If I treat a char[] like an int[] indexing through it in memory at a low level wouldn't work. A step of 4 bytes (treating like int[]) would actually step 2 indices in a char[].

like image 42
rfeak Avatar answered Jan 28 '23 10:01

rfeak