strendey
strendey

Reputation: 27

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?

Upvotes: 1

Views: 145

Answers (1)

Gautham M
Gautham M

Reputation: 4935

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"));

Upvotes: 2

Related Questions