Thursday, 17 January 2013

Apache Commons Lang Library : Managing Strings without NullPointers

The Apache Commons Lang 3.0 package is a useful set of utilities and interface definitions for String and Character manipulation. With respect to String manipulation, the StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils classes provide a number of utility methods for manipulating and managing String.

The StringUtils class has some interesting functions such as 
  • IsEmpty/IsBlank - checks if a String contains text. The main difference between IsEmpty and IsBlank is that that IsBlank also checks for whitespaces while IsEmpty doesn't. 
  • Trim/Strip - removes leading and trailing whitespace
  • Equals - compares two strings null-safe
  • startsWith - check if a String starts with a prefix null-safe
  • endsWith - check if a String ends with a suffix null-safe
  • IndexOf/LastIndexOf/Contains - null-safe index-of checks
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
  • ContainsOnly/ContainsNone/ContainsAny - does String contains only/none/any of these characters
  • Substring/Left/Right/Mid - null-safe substring extractions
  • SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
  • Split/Join - splits a String into an array of substrings and vice versa
While these functions may appear similar to the ones provided by the String package itself, the StringUtils versions are null safe thus eliminating the possiblity of those horrible NPEs. It should be noted that a null input will return null without throwing any exception.

No comments: