How to check if a field in an array of chars is empty in Java?

-2

I'm trying to check if a certain position in an array of chars actually contains some character.

I tried two ways:

char[] arr = new char[10];

if(arr[0] == null){

}

And also:

char[] arr = new char[10];
if(arr[0] == ''){

}

When typing any of the code versions above, Netbeans points to error in the comparison, but does not suggest correction.

How can I do this verification?

    
asked by anonymous 28.07.2018 / 02:09

1 answer

1

I believe there is no "empty" representation for type char which is primitive, such as '' , so you have to analyze it in a different way. I looked in the documentation for class Character and found the MIN_VALUE which is a constant for the value '\u0000' which in this case is 0 (zero).

See an example:

import java.lang.*;

class Main 
{
  public static void main(String[] args) 
  {
    char[] arr = new char[] {'a','b', Character.MIN_VALUE};
    if (arr[1] == Character.MIN_VALUE)
    {
      System.out.println("vazio");
    }    
    else 
    {
      System.out.println("nao vazio");
    }
  }
}

Output:

  

not empty

So, for better fix see this table with default values for all primitive types:

Table Font

If you want "empty" values in the array you can use this constant. There's this question too. Always try to prioritize documentation in your searches, if you do not have it you can ask here.

    
28.07.2018 / 05:58