Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

char

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.

like image 226
user1090944 Avatar asked Feb 25 '16 07:02

user1090944


People also ask

What is the default value of a char data type elements of an array in?

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

What is the default value of an array of objects in Java?

In Java, objects initializations assume the default value "null".

What is default value of char array in C?

For char arrays, the default value is '\0' . For an array of pointers, the default value is nullptr . For strings, the default value is an empty string "" . That's all about declaring and initializing arrays in C/C++.

What does a char array initialize to in Java?

A char array can be initialized by conferring to it a default size. char [] JavaCharArray = new char [ 4 ]; This assigns to it an instance with size 4.


1 Answers

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

like image 74
Jon Skeet Avatar answered Sep 19 '22 21:09

Jon Skeet