DEV Community

Cover image for Finding Null or Empty String Checks in Java
Gunnar Gissel
Gunnar Gissel

Posted on • Updated on • Originally published at

Finding Null or Empty String Checks in Java

I have a lot of code like this:

if( null == myString || "".equals(myString))
Enter fullscreen mode Exit fullscreen mode

The codes fine, really. Very idiomatic, gets the job done.

Lately, I've been on a predicate kick. I like replacing my conditionals with predicates that describe the intent of the conditional statement. I can also replace a lot of my boilerplate code with a couple common predicates. This is one I use a lot:

 public static final Predicate<String> NULL_OR_EMPTY = (in) -> null==in || "".equals(in);
Enter fullscreen mode Exit fullscreen mode

It's true; if the code base had been crafted with Optionals or other null-avoidance techniques, that I could mostly ignore this check. My code base has history and weight and external interfaces, so there are plenty of this check and others like it.

I have been using this regex to find likely places that I can apply my predicate:

Enter fullscreen mode Exit fullscreen mode

It's an ugly one, but it matches a lot of common patterns for checking if a string is null or empty. I'm hopeful that folks will suggest either a better way of finding null or empty checks or help me add to my hideous regex!

Get a monthly email with great tech and tech leadership articles from around the web

Thanks to Jan Tik for the header image

Follow me at my blog!

Top comments (2)

niharmore33 profile image

You should leverage StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
Learn Java here:


System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).


System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

monknomo profile image
Gunnar Gissel

That's in Apache Commons, right? It's a very useful library, and if I have it in a project already, I'm going to use it, but if I don't already have it, I won't. Guava is great too, and starting from scratch I generally toss it in.

In this particularly case I'm dealing with a large established code base that is politically resistant to new libraries. Being that it is established, it has many different patterns from different eras of development. The regex is part of an effort to track down some of those patterns and unify them, without adding a library. I think it is pretty obvious that you wouldn't use a regex to find a pattern of coding in a new project - this is for old projects that may not have always done it the right way.

I would be interested if you know of a better way to find more null or empty checks in strings than just adding to my regex when I find a new pattern