Checking If a String Is Empty or Null in Java

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

Best way to verify string is empty or null

Haven't seen any fully-native solutions, so here's one:

return str == null || str.chars().allMatch(Character::isWhitespace);

Basically, use the native Character.isWhitespace() function. From there, you can achieve different levels of optimization, depending on how much it matters (I can assure you that in 99.99999% of use cases, no further optimization is necessary):

return str == null || str.length() == 0 || str.chars().allMatch(Character::isWhitespace);

Or, to be really optimal (but hecka ugly):

int len;
if (str == null || (len = str.length()) == 0) return true;
for (int i = 0; i < len; i++) {
if (!Character.isWhitespace(str.charAt(i))) return false;
}
return true;

One thing I like to do:

Optional<String> notBlank(String s) {
return s == null || s.chars().allMatch(Character::isWhitepace))
? Optional.empty()
: Optional.of(s);
}

...

notBlank(myStr).orElse("some default")

String blank (empty or null) check : if structure vs java 8 optional/filter

Question: Which approach is better and why

The first one, because in the second one you create an unnecessary Optional


But I would suggest to use isNotEmpty instead of isNotBlank:

if(StringUtils.isNotEmpty(str)){
list.add(str)
}

To know the difference between isNotEmpty and isNotBlank in doc:

Checks if a CharSequence is not empty ("") and not null.

Checks if a CharSequence is not empty (""), not null and not whitespace only.

In your case you ask null or empty, where isNotEmpty is the correct one for your case.

How to check a string that not empty in java?

You can see if the characters match

if (str.equals ("")) {
// true
}

if (str3.equals (" ")) {
// true
}

how to check if the variable is null?

you can use .equals("") or .isEmpty()

check check if the variable is null

Difference between null and empty () Java String

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.



Related Topics



Leave a reply



Submit