What are the default values ​​for a char array in Java?

If I allocate an array of characters as follows:

char[] buffer = new char[26]; 

What are the default values ​​to which it is assigned? I tried to print it and it is just an empty character.

 System.out.println("this is what is inside=>" + buffer[1]); this is what is inside=> 

Is there an ASCII code for it? I need to determine if the array is empty or not, and then, when I fill, say the first five elements with characters, I need to find out that the sixth element is empty. Thanks.

+2
source share
1 answer

Same as for any type: default value for this type. (Just as you would enter a field that was not specifically initialized.)

The default values ​​are specified in JLS 4.12.5 :

For char, the default value is the null character, that is, '\u0000' .

Having said that, it looks like you want a List<Character> that can track the actual size of the collection. If you need random access to the list (for example, you want to be able to fill element 25, even if you do not have element 2 populated), then you might think:

  • A Character[] using null as the value "not set" instead of '\u0000' (which, after all, is still a character ...)
  • A Map<Integer, Character>
  • If you know that you never want to consider an element with a value of '\u0000' as "set"

(It is hard to know which one is the most suitable without knowing more about what you are doing.)

+7
source

Source: https://habr.com/ru/post/1276079/


All Articles