In this blog, we will learn about the StringUtils class. It provides some nice utilities that deal with Strings as compare to java.lang.String. Before discussing its methods, let’s see one example.
what if the movie’s name is Null. 🤔
Then definitely it will throw a Null Pointer Exception.
Yes, java.lang.String methods are not null safe.
OK, let me modify the above code.
Now, no more null pointer exception. But I think these null checks make your code dirty.
So, Here comes StringUtils class in the picture. Though there are plenty of third-party libraries that solve the problem, here I am discussing StringUtils only.
What is StringUtils?
StringUtils class is provided by Apache Commons Lang 3 Library which consists of null safe methods. The class consists a lot many utility methods, all of which are very difficult to cover here, so we’ll take a look at some of the widely used methods. To get started with the StringUtils first thing we need to do is to add the dependency to our Maven-Project.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<dependency> | |
<groupId>org.apache.commons</groupId> | |
<artifactId>commons-lang3</artifactId> | |
<version>3.8.1</version> | |
</dependency> |
Now let’s quickly go through the utility methods it provides:
1) isEmpty() – Checks if the String contains text
2) isBlank() – Checks if the String contains text and moreover it also checks for the whitespace.
isBlank() = (isEmpty() + check whether the text contain white space)
StringUtils also has isNotBlank() and isNotEmpty() methods which are equivalent to !isBlank() and !isEmpty() respectively.
3) swapCase() : Swaps the case of the text. It simply converts lowercase to uppercase and viceversa.
In case of a null and empty string, swapcase() simply return null and empty string respectively.
4) trim(): Removes every whitespace and control character from the begining and the end of the received string.
5) join(): Joins the elements of the provided array into a single string.
You can get all the methods here .
Conclusion
StringUtils provide the same method as String class but these methods are null safe. So basically if you want to avoid Null Pointer Exception, take a look at StringUtils.
Hope this is helpful. Please feel free to provide your suggestions 🙂
References:
https://www.baeldung.com/string-processing-commons-lang
https://www.codebyamir.com/blog/using-stringutils-from-apache-commons-lang-3