Skip to content
Advertisement

Java Null check fails and code proceeds to if statement

I have an if condition within my code and I do not want my code to proceed into the if condition if the value of the variable is Null but for some reason, the condition passes and proceeds to the next part but the value of the field is NULL.

I am not sure why this issue is happening. A similar approach works for the other fields but not for this field:

if (myField != null) {
 System.out.println("WITHIN IF : " + myField);
//prints null
}

I researched a bit tried a couple of things like:

if(!Objects.isNull(myField))

In following cases the condition fails saying that java.lang.NullPointerException: Cannot invoke "String.equalsIgnoreCase(String)" because the return value of toString() is null

if(myField != null && myField.toString().equals("null"))
if(myField != null && myField.toString().equalsIgnoreCase("null"))

I am not understanding what’s going wrong here. The value is null but the check fails and it goes within my If condition. If I try to convert to toString() then it fails saying the value is null.

Can someone please help me with this issue?

Advertisement

Answer

When java calculate value of "WITHIN IF : " + myField expression it calls toString method on myField object.

It could return string "null" or it could return actual null reference. In both cases you will get "WITHIN IF : null" as result.

PS: you have second case at hand.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement