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?

Recommended Answers

All 7 Replies

...deleted

...deleted

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

if(a == null)
{
    System.out.println("a is null.");
}
Member Avatar for ztini
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
}

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

if(a == null || a.length() == 0) {
}
commented: Wrong -1
commented: Not sure what ztini is talking about. This is fine. +15

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,

if(!"".equals(someString))

which enables to avoid an explicit null-check and NPE

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.