# Java Programming > Java Programming >  Java equals() selection

## Nathan D

In Java, if I try to do.equals() on a null string, a null pointer error is issued. Im wondering whether I can perform the following if Im attempting to compare if a string is equal to a constant string:


```
MY CONSTANT STRING.equals(aStringVariable)
```

Im sure itll work, but is this simply extremely bad code?
This is a common Java idiom known colloquially as a Yoda condition. Personally, I prefer to handle the null situation directly, but the Yoda method is widely used, and any competent Java programmer should quickly grasp what is going on. How should I proceed?

----------


## wolle

> How should I proceed?


If the null pointer has meaning and represents "nothing" or "empty" or something of that kind, I would use the Yoda condition. Otherwise, the null pointer is an error, and I would check for it directly. 

Tony Hoare, the inventor of the null pointer, calls it his billion-dollar mistake. The best strategy is to avoid them. You may search the internet for suggestions.

----------


## andbin

> In Java, if I try to do.equals() on a null string, a null pointer error is issued.


Sorry for late answer but I regained the login on this forum only today.

Yes, you get a NullPointerException. And if you want to avoid this, there are some possibilities:

1) The classic null-safe explicit test:

if (yourStr != null && yourStr.equals("expected"))

2) The static equals() in java.util.Objects (JDK 7+) which is null-safe:

if (Objects.equals(yourStr, "expected"))

3) There is a similar static utility in notable libraries like Google Guava

----------

