Need a proof? Feed “java StringUtil” to your favorite search engine – I found 20 different implementations among the first 30 search hits only!
There is a simple reason for that – Strings are used quite frequently in common Java programs (especially when UI is involved), and the
java.lang.String class itself offers only a very limited API for String operations.
Since almost everybody needs String utilities and the JDK does not provide them, there are plenty of third-party open source libraries filling the gap with their own implementations. So why are people not using them and writing their own utilities instead? I suspect the do-it-yourself approach is very tempting since the problems in this domain are usually easy to understand, the solution code is mostly short and not too hard to implement. Writing a two-liner yourself seems to be faster than digging through JavaDoc or code of third-party libraries to find a method solving your String problem.
But this is deceiving – even a two-liner can contain plenty of bugs, needs to be tested and maintained.
Here are some proven and commonly used open source String utility implementations:
The leader of the pack – Apache Commons
Apache Commons has been around for more than 10 years now. Its language component offers several utility classes with null-safe methods for String parsing and manipulation. Also more powerful versions of
StringBuilder can be found. Check out the packages
org.apache.commons.lang3.text for details.
Make sure you use version 3 which supports Java 5 language features like generics.
The contender – Google Guava
Google Guava version was first released in 2009 and has delevoped into a serious alternative or complement to Apache Commons since then. It supported Java generics from the beginning and has a more modern API than Commons.
Google Guava has powerful tools for joining and splitting Strings, character matching and word handling. See the JavaDoc of package
com.google.common.base or look at the excellent Wiki page about Strings.
The alternative – Spring framework
If you’re a Spring addict, the Spring framework will be part of your project anyway. Then you can as well use org.springframework.util.StringUtils which offers 40+ static methods for String parsing and manipulation.
There are many good reasons to use String utilities from third-party libraries:
- They’ve been tested well
- They’ve been used successfully in hundreds of projects
- They’re mostly bug-free
Unless you have been infected with the NIH syndrome, or work in a project with severe restrictions on which libraries to use, there is no good argument for implementing String utilities yourself. So go ahead and clean up your code!