-2

In the getter of my class the attribute may have null value from database :

public String getCible() {
    return cible.equals(null) ? " - " : cible;
}

In my code I want to call this getter , but I got NullPointerException.

If I change the comparison to return cible == null ? " - " : cible; then everything is wright :) So why ?

pheromix
  • 18,213
  • 29
  • 88
  • 158
  • 3
    It is not impossible to compare a `string` with `null`. The point is it is impossible to call a method on a `null` value – Jens Apr 27 '17 at 13:45
  • 1
    equals and == are two different things. see full explanation here: http://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java You can use org.apache.commons.lang.ObjectUtils.equals(cible, null) or of its a string then org.apache.commons.lang.StringUtils.equals(cible, null) which is null safe – poozmak Apr 27 '17 at 13:52

1 Answers1

3

You call a method on a null, so it is like null.equals(null), null has no methods so it throws the exception.

If you dont want to use ==, you can use Objects.equals(yourString, null)

Shadov
  • 5,421
  • 2
  • 19
  • 38