How do I check that a Java String is not all whitespaces?
Checking for non-whitespace characters in a Java String is as straightforward as using str.trim().isEmpty()
or !str.isBlank()
for Java 11+. For compact approaches, consider StringUtils.isNotBlank(str)
from the Apache Commons Lang library. Here's the basic concept:
For antiquated Java versions, we do:
But don't rush off just yet - let's dive deeper into the intricacies of these methods, alternatives and important considerations!
Unicode and Regex to the rescue!
Standard .trim
method is a great chap, but alas he's not adept with Unicode! Fear not, a detailed regex pattern is here to carry the day. Introducing .*\\S.*
, adept at handling Unicode non-whitespace characters:
Before you get all excited, performance could be an issue here. Avoid overworking poor regex - save it for emergencies.
Null and empty - the insidious twins
Nothing quite puts a damper on your code's jamboree like a NullPointerException. So, remember to check if the string is null
before messing with it:
A little tip from me to you, str.trim()
will always give you back something, either an empty string or a trimmed string. It's not the disappearing type.
Java 8+ Streams for the modern coder
If you're part of the stream
team, Java 8+ Streams can be your magic wand to identify non-whitespace:
A dose of functional programming makes your string operations fun and elegant. Exercise caution, streams can run wild.
StringUtils - your swiss army knife
If you're a fan of Apache Commons Lang, wield the StringUtils.isNotBlank(str)
method - it's sharper than a trim
:
This method grabs null
, empty and whitespace-only strings by the collar and tidies them up.
Regular expressions - Tough to master, sweet to use
While regex tools are the 'black belt' in string manipulation, remember their impact on cost and readability are equivalent to a turtle carrying a piano. Fast? No. Impressive? Definitely.
Anticipate the mischievous edge cases: Null, empty, filled with non-printable character strings! They can ruin your perfect program if left unattended.
Characters, characters everywhere
Everyone's unique, and so is the whitespace in your strings. Java 11's isBlank()
is social and acknowledges this diversity, including spaces, tabs, and new line characters.
References
Was this article helpful?