Can we rely on String.isEmpty for checking null condition on a String in Java?

I am passing an accountid as input from an XML file as shown, which will be parsed later and will be used in our code:


The issue is that if nothing is passed (null value in accoutnid) is passed as accountid, I could not able to handle that situation in Java code. I tried this but I was not successful:

if (acct != null||acct==""||acct.equals("")) 
    // the above is not working 

I was able to handle this successfully using the following approach:

   // thisis working 

Can we rely on the String.isEmpty() method for checking the null condition of a String? Is this valid?


No, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.

Your test should be:

if (acct != null && !acct.isEmpty())

Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.

Alternatively, using Guava:

if (!Strings.isNullOrEmpty(acct))