Set size on char array in Java

VansFannel picture VansFannel · Oct 16, 2010 · Viewed 28.6k times · Source

I'm developing an Android application.

I want to set size to a char array like this:

public char[5] language;

But it doesn't work. I have to delete number five to make it work.

I want to limit to five characters to language variable. How can I do that?

Thanks.

Answer

Stephen C picture Stephen C · Oct 16, 2010

You cannot do it like that. In Java, the type of an array does not include it's size. See my answer to this earlier question. (Ignore the part about abstract methods in that question ... it's not the real issue.)

The size of an array is determined by the expression that creates it; e.g. the following creates a char array that contains 5 characters, then later replaces it with another array that contains 21 characters.

public char[] language = new char[5];
...
language = new char[21];

Note that the creation is done by the expression on the RHS of the equals. The length of an array is part of its 'value', not its 'type'.