简体   繁体   中英

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.

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

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 '\' (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 '\' as "set"

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

You can also convert it to int and then compare.
for ex - Suppose I declare my array as

char[] arr = new char[10];
arr[3]='1';

Then, the below code

for(char c:arr){
    if((int)c!=0){
        System.out.println(c);
    }
}

Will output

1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM