Both null and empty char are equal in java

3.5k Views Asked by At

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
}
4

There are 4 best solutions below

1
On BEST ANSWER

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");
0
On

Empty chars are not null. They don't just hold any value.

Yes. You should check both if your column allow nulls. Also, your code might give you NullPointerException since you are first checking for empty char and then for null. Better to use below

if(someObject.getSomeCharValue()==null || someObject.getSomeCharValue()=='' )
6
On
if(someObject.getSomeCharValue()=='' && someObject.getSomeCharValue()==null)

both someObject.getSomeCharValue()=='' and someObject.getSomeCharValue()==null are compilation error.

if there is no value in the DB that means it is null but not empty char.

There is nothing called empty char ('') in Java.
But there is empty string ("").

0
On

Empty char

//Empty character literal does not exist in Java.
char c = ''; //does not compile

A Null Literal in Java

The null type has one value, the null reference, represented by the null literal null, which is formed from ASCII characters.

is different from the

Null character

The null character (also null terminator) is a control character with the value zero.

Today the character has much more significance in the programming language C and its derivatives and in many data formats, where it serves as a reserved character used to signify the end of a string,[6] often called a null-terminated string.

Excellent article about Null in Java