How to check if a char is null

34,313

Solution 1

A char cannot be null as it is a primitive so you cannot check if it equals null, you will have to find a workaround.

Also did you want to check if letterChar == ' ' a space or an empty string? Since you have a space there.

The first two answers here may be helpful for how you can either check if String letter is null first.

or cast char letterChar into an int and check if it equals 0 since the default value of a char is \u0000- (the nul character on the ascii table, not the null reference which is what you are checking for when you say letterChar == null)- which when cast will be 0.

Solution 2

char is a primitive datatype so can not be used to check null.

For your case you can check like this.

        if (letterChar  == 0) //will be checked implicitly
        {
            System.out.println("null");
        }
        //or use this
        if (letterChar  == '\0')
        {
            System.out.println("null");
        }
Share:
34,313

Related videos on Youtube

Cheeseburger
Author by

Cheeseburger

Updated on April 21, 2021

Comments

  • Cheeseburger
    Cheeseburger about 3 years

    I want to check if the char is null or not? but why this code is not working? letterChar == null also is not working. I googled for many problems but didn't see any solutions, mostly the solutions are about String.

    String letter = enterletter.getText().toString();
    char letterChar = letter.charAt(0);
    
    
    if(letterChar == ' ' || letterChar == NULL) // this is where the code won't works
    {
        Toast.makeText(getApplicationContext(), "Please enter a letter!", Toast.LENGTH_LONG).show();
    }
    
    • statosdotcom
      statosdotcom about 6 years
      Char? Why not use string?
    • ADM
      ADM about 6 years
    • Cheeseburger
      Cheeseburger about 6 years
      @statosdotcom because I want the user to enter character only
    • Meet Patel
      Meet Patel about 6 years
      You can achieve you result wit this: String letter = enterletter.getText().toString().trim(); // this will remove whitespace if(letter.length()<1){ Toast.makeText(getApplicationContext(), "Please enter a letter!", Toast.LENGTH_LONG).show(); }
    • Sachin Rajput
      Sachin Rajput about 6 years
      @burger , check the answer below it will work.