I have a string, which is read from a database. The string can be just "null". I need to decide whether it is null or not? Among the following ones, what is the appropriate way to do it?

String a = …;
If  (a == null)

If ( a.length == 0)

I also see something like

If ( a.equals(“ “))

How does this work?

7 Years
Discussion Span
Last Post by mKorbel

To test whether a String a is null, just do this...

if(a == null)
    System.out.println("a is null.");

Edited by VernonDozier: Here's the good post. Sorry for the bad ones.

if(a == null) {
    System.out.println("a is null.");

Vernon is correct, that is how you test to see if the object is null (in this case the object is instantiated as a String). However, to see if the data contained in the String itself is null, you need to perform some additional checking.

This is why you might want to do:

if (a.equals("")) {
     // do something clever

Edited by ztini: n/a


If, for your application, a null String and a zero size String are equivalent you can:

if(a == null || a.length() == 0) {
Votes + Comments
Not sure what ztini is talking about. This is fine.

ztini so fast on down voting people.
Length is better approach then equal, for once length check is used in string native method isEmpty()

PS: Maybe time to start reading another interesting book like Effective Java
PS2: If you decide to down vote and leave comment then make it meaningful.


@pbl you missed .trim()

@ztini your 2nd. code "if (a.equals("")) {" is total nonsenceas as answer for OP's, no never use that, nor to advice for someone

real code would be

if(a == null || a.trim().length() == 0) {

for OOP and class that can returs null value is there simple hack or for ignore null value with NPE too, and alyways returns true,


which enables to avoid an explicit null-check and NPE

Edited by mKorbel: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.