Search code examples
javadatabasenullchar

Both null and empty char are equal in java


I have doubt while taking a null or empty char check in Java. Is both have to be checked in any way.

For example in database the variable length for Char is 1 . It will allow null as well. So if you have empty char does it mean null? or we have to check as

if(someObject.getSomeCharValue()=='' && someObject.getSomeCharValue()==null) {
    //true
}
else{
    //dont compile
}

Solution

  • char has no value with ''. In char, null character (or empty char) is \0 or \u0000. You can't check with '' or null.

    For example if you declare a char like this:

    char c = '';//compilation error here
    

    or

    char c = null;//compilation error here
    

    so if you want to check whether a char is null, then you need to use the following code:

    char c = '\0';
    if (c == '\0') System.out.print("char is null");//if(c == '\u0000') also can be possible
    else System.out.print("char is not null");