Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set size on char array in Java

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.

like image 654
VansFannel Avatar asked Jul 04 '26 03:07

VansFannel


2 Answers

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'.

like image 146
Stephen C Avatar answered Jul 05 '26 17:07

Stephen C


To quote the JLS :

An array's length is not part of its type.

To initialize an array you should do :

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

Other solutions are

public char[] language = {0, 0, 0, 0, 0};

or

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

In Java, the array declaration can't contain the size of the array; we only know the variable will contain an array of a specific type. To have an array initialized (and with a size) you have to initialize it either by using new or by using a shortcut which allows to initialize and set values for an array at the same time.

Best way to have to check if an array has a specified size, is actually checking the size of the array yourself with something like if(array.length == 5).


Resources :

  • JLS - Array Types
  • JLS - Array Creation Expressions

On the same topic :

  • abstract method of a set length array in java?
like image 21
Colin Hebert Avatar answered Jul 05 '26 15:07

Colin Hebert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!