How to Check If My String Is Equal to Null

Check whether a String is not Null and not Empty

What about isEmpty() ?

if(str != null && !str.isEmpty())

Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.

Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.


To ignore whitespace as well:

if(str != null && !str.trim().isEmpty())

(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)

Wrapped in a handy function:

public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}

Becomes:

if( !empty( str ) )

How to check if String is null

An object can't be null - the value of an expression can be null. It's worth making the difference clear in your mind. The value of s isn't an object - it's a reference, which is either null or refers to an object.

And yes, you should just use

if (s == null)

Note that this will still use the overloaded == operator defined in string, but that will do the right thing.

How do I check if two strings are equal in Java when either one of the strings can be a null?

You do not need to create a new method for that. You can use java.util.Objects#equals(Object a, Object b) from the Java standard library. Below is the definition as on JDK.

public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}

Java string null check by != null or !str.equals(null)?

1st one is better (and the only option), because 2nd one will throw NPE, when your value is actually null. As simple as that.

Try this out:

String str = null;
str.equals(null); // will throw `NPE`.

So basically, the test which you wanted to perform itself triggers a NullPointerException in the 2nd case. So, it is no choice.

Do I need to check null and while comparing String in Java?

There is no way that "Hello".equals(str)) would ever fail, a string literal simply can never be null. Same thing with "".equals(str).

The method Objects.equals(Object, Object) automatically checks nulls first.


To answer your question, using if ("Hello".equals(str)) is just fine, but if you ever want to replace the string literal "Hello" by a variable, you should use Objects.equals(greeting, str).

Checking for an empty string is absolutely unnecessary.



Related Topics



Leave a reply



Submit