Home > Software engineering >  If statemet with || wont work in java android
If statemet with || wont work in java android

Time:06-04

Hello i have this simple code:

if(IssCodeRef.equals("") || IssCodeRef == null){
return -1;
}

the problem is that when my value is null it doesnt go to -1 but straight to error and my app crashes. But works fine when value is ""

I can try to make longer if like

  if(IssCodeRef.equals(""){
    return -1;
    }else if IssCodeRef == null){
     return -1;
    }

But i dont really like it as a solution any idea why the null part wont be checked when is inside || ?

CodePudding user response:

The immediate fix would be to check for null first:

if (IssCodeRef == null || IssCodeRef.equals("")) {
    return -1;
}

But a better approach is to use the following trick:

if ("".equals(IssCodeRef) || IssCodeRef == null) {
    return -1;
}

Here we put the string literal, in this case "", on the LHS of the comparison, and therefore it will never throw an exception, even if IssCodeRef happens to be null. So we can check for empty string first in this version and get away with it.

CodePudding user response:

You are checking for null, then you need to check white space also.

   public static boolean isEmptyStr(String Val) {
        if (Val == null || Val.isEmpty() ||  Val.trim().isEmpty() || Val.equalsIgnoreCase("null"))
            return true;
        else
            return false;
    }

call it like this; boolean isNull = isEmptyStr(IssCodeRef); and you can use that boolean for your next logic.

  • Related