IntelliJ warns NullPointerException

I have a method that can return a String and can be a null value, using this code:

private static boolean hasSignificantValue(String identificator) {
    String content = variables.get(identificator); //method
    System.out.println(content == null);
    return (variables.exists(identificator) && content.length() > 0 && !content.equals("null"));
}

However, commenting on the exit, I no longer receive this warning

private static boolean hasSignificantValue(String identificator) {
    String content = variables.get(identificator);
    return (variables.exists(identificator) && content.length() > 0 && !content.equals("null"));
}

Why does it happen?

Answer

System.out.println(content == null); this line indicates that content could possibly become a null, so which would possibly cause a NullPointerException in content.length(). So the IDE warns about a potential NullPointerException.

So once you remove the null check, then the IDE doesn’t see a scenario where content would be null (Even though it could still be null but there is no explicit null check). Hence the warning will not be shown in this case.

So you could do:

String content = variables.get(identificator); //method
if(content == null) {
    System.out.println("Content is null");
    return false;
}

// Execution would reach here only if content is not null. Hence no warning is displayed.
return (variables.exists(identificator) && content.length() > 0 && !content.equals("null"));

Leave a Reply

Your email address will not be published. Required fields are marked *