How to check if my string is equal to null?
To check if a string is equal to null
in Java, you can use the ==
operator.
Here is an example of how you can check if a string is null
:
String str = null;
if (str == null) {
// The string is null
}
Alternatively, you can use the Objects.isNull()
method from the java.util.Objects
class, like this:
import java.util.Objects;
String str = null;
if (Objects.isNull(str)) {
// The string is null
}
Note that you should not use the equals()
method to check if a string is null
, because this will result in a NullPointerException
if the string is indeed null
.
Here is an example of what not to do:
String str = null;
if (str.equals(null)) { // This will throw a NullPointerException
// The string is null
}