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 couple of way 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 are 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 ofchecking 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 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. Another popular and faster wayto check if String is empty or not is by checking it's length, e.g. if String.length() = 0 then String is empty, but this is also not null safe. Third common way of checking emptiness of String in Java is comparing it with empty String literal e.g. "".equals(str),this method is not as fast as previous two but it is null safe, you don't need to check for null, in case of null it will return false. So in my opinion, this is the right way to check if String is empty or not. If you definition of empty String also includes null then you can also use Apache Commons Lang's StringUtils class. It has methods like isEmpty() which return true for both null and empty String literal. Again this is also null safe and will not throw NullPointerException.
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment