Right way to check if String is empty in Java
What do you most of us do
while using String in Java? checking whether String is null or empty right? I
am sure you know a couple of ways to test whether String is empty or not, but
do you know the right way to do it? When we talk about Strings in Java, we can imagine them as arrays
of characters, and they are, but in Java, they also object. An empty Java
String is considered as the not null String that contains zero characters,
meaning its length is 0. However, a Java String that might only contain the
white-space character is not considered as empty, it is considered to contain
one character and its length is equal to 1. One of the most popular way of checking
whether String is empty or not is String class' isEmpty() method,
this looks perfect right, it's readable and returns boolean if String is empty
otherwise returns false, but the problem is you can not call this method
without checking whether String is null or not. In another word, this is not
null safe and it will throw NullPointerException if String is null.