How to check whether an element of a character array is empty?

I need to check if an element of a java array of characters is empty. I tried out the following code but didn't work. What's wrong?

char c[] = new char[3];
c[0] = 'd';

for (int i = 0; i < c.length; i++) {
    if(c[i] == null) {
        System.out.println(i + " is empty");
    }
}
Jon Skeet
people
quotationmark

Let's take arrays out of the equation - an array is just a collection of variables, really. Let's consider a single variable. Suppose we had a method like this:

public boolean isEmpty(char c)

What would that do? The value of c cannot be null, because char is a primitive type. It could be U+0000 (aka '\u0000' or '\0' as character literals in Java), and that's the default value of char (for array elements and fields) but it's not the same as a null reference.

If you want a type which is like char but is a reference type, you should consider using Character - the wrapper type for char just like Integer is for int. Or if you know that you'll never use U+0000 as a valid value, you could just stick with that.

However, a better alternative would often be to design your code so that you don't need the concept of "empty or not empty". We don't know what you're trying to achieve here, but it's usually a good thing to at least consider. For arrays, the alternative is often to use an ArrayList<E> - but of course you can't have an ArrayList<char> in Java as Java generics don't allow primitive type arguments :(

people

See more on this question at Stackoverflow