What are the default values of the char array in Java?

If I allocate array of characters like this:

char[] buffer = new char[26];

what are the default values it is allocated with? 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 be able to determine if the array is empty or not, and further on, when I fill say first five elements with chars, I need to find out that the sixth element is empty. Thanks.

Jon Skeet
people
quotationmark

It's the same as for any type: the default value for that type. (So the same as you'd get in a field which isn't specifically initialized.)

The default values are specified in JLS 4.12.5:

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

Having said that, it sounds like really you want a List<Character>, which can keep track of the actual size of the collection. If you need random access to the list (for example, you want to be able to populate element 25 even if you haven't populated element 2) then you could consider:

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

(It's hard to know which of these is the most appropriate without knowing more about what you're doing.)

people

See more on this question at Stackoverflow