Wednesday, November 2, 2011

Guava's Strings Class

In the post Checking for Null or Empty or White Space Only String in Java, I demonstrated common approaches in the Java ecosystem (standard Java, Guava, Apache Commons Lang, and Groovy) for checking whether a String is null, empty, or white space only similar to what C# supports with the String.IsNullOrWhiteSpace method. One of the approaches I showed was a Guava-based approach that made use of the Guava class Strings and its static isNullOrEmpty(String) method. In this post, I look at other useful functionality for working with Strings that is provided by Guava's six "static utility methods pertaining to String" that are bundled into the Strings class.

Using Guava's Strings class is straightforward because of its well-named methods. The following list enumerates the methods (all static) on the Strings class with a brief description of what each does next to the method name (these descriptions are borrowed or adapted from the Javadoc documentation).

isNullOrEmpty

Guava's Strings.isEmptyOrNull(String) method makes it easy to build simple and highly readable conditional statements that check a String for null or emptiness before acting upon said String. As previously mentioned, I have briefly covered this method before. Another code demonstration of this method is shown next.

Code Sample Using Strings.isNullOrEmpty(String)
   /**
    * Print to standard output a string message indicating whether the provided
    * String is null or empty or not null or empty. This method uses Guava's
    * Strings.isNullOrEmpty(String) method.
    * 
    * @param string String to be tested for null or empty.
    */
   private static void printStringStatusNullOrEmpty(final String string)
   {
      out.println(  "String '" + string + "' "
                  + (Strings.isNullOrEmpty(string) ? "IS" : "is NOT")
                  + " null or empty.");
   }

   /**
    * Demonstrate Guava Strings.isNullOrEmpty(String) method on some example
    * Strings.
    */
   public static void demoIsNullOrEmpty()
   {
      printHeader("Strings.isNullOrEmpty(String)");
      printStringStatusNullOrEmpty("Dustin");
      printStringStatusNullOrEmpty(null);
      printStringStatusNullOrEmpty("");
   }

The output from running the above code is contained in the next screen snapshot. It shows that true is returned when either null or empty String ("") is passed to Strings.isNullOrEmpty(String).

nullToEmpty and emptyToNull

There are multiple times when one may want to treat a null String as an empty String or wants present a null when an empty String exists. In cases such as these when transformations between null and empty String are desired, The following code snippets demonstrate use of Strings.nullToEmpty(String) and Strings.emptyToNull(String).

nullToEmpty and emptyToNull
   /**
    * Print to standard output a simple message indicating the provided original
    * String and the provided result/output String.
    * 
    * @param originalString Original String.
    * @param resultString Output or result String created by operation.
    * @param operation The operation that acted upon the originalString to create
    *    the resultString.
    */
   private static void printOriginalAndResultStrings(
      final String originalString, final String resultString, final String operation)
   {
      out.println("Passing '" + originalString + "' to " + operation + " produces '" + resultString + "'");
   }

   /** Demonstrate Guava Strings.emptyToNull() method on example Strings. */
   public static void demoEmptyToNull()
   {
      final String operation = "Strings.emptyToNull(String)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.emptyToNull("Dustin"), operation);
      printOriginalAndResultStrings(null, Strings.emptyToNull(null), operation);
      printOriginalAndResultStrings("", Strings.emptyToNull(""), operation);
   }

   /** Demonstrate Guava Strings.nullToEmpty() method on example Strings. */
   public static void demoNullToEmpty()
   {
      final String operation = "Strings.nullToEmpty(String)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.nullToEmpty("Dustin"), operation);
      printOriginalAndResultStrings(null, Strings.nullToEmpty(null), operation);
      printOriginalAndResultStrings("", Strings.nullToEmpty(""), operation);
   }

The output from running the above code (shown in the next screen snapshot) proves that these methods work as we'd expect: converting null to empty String or converting empty String to null.

padStart and padEnd

Another common practice when dealing with Strings in Java (or any other language) is to pad a String to a certain length with a specified character. Guava supports this easily with its Strings.padStart(String,int,char) and Strings.padEnd(String,int,char) methods, which are demonstrated in the following code listing.

padStart and padEnd
   /**
    * Demonstrate Guava Strings.padStart(String,int,char) method on example
    * Strings.
    */
   public static void demoPadStart()
   {
      final String operation = "Strings.padStart(String,int,char)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.padStart("Dustin", 10, '_'), operation);
      /* Do NOT call Strings.padStart(String,int,char) on a null String:
       *    Exception in thread "main" java.lang.NullPointerException
     *         at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
     *         at com.google.common.base.Strings.padStart(Strings.java:97)
       */
      //printOriginalAndResultStrings(null, Strings.padStart(null, 10, '_'), operation);
      printOriginalAndResultStrings("", Strings.padStart("", 10, '_'), operation);      
   }

   /**
    * Demonstrate Guava Strings.padEnd(String,int,char) method on example
    * Strings.
    */
   public static void demoPadEnd()
   {
      final String operation = "Strings.padEnd(String,int,char)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.padEnd("Dustin", 10, '_'), operation);
      /*
       * Do NOT call Strings.padEnd(String,int,char) on a null String:
       *    Exception in thread "main" java.lang.NullPointerException
     *         at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
     *         at com.google.common.base.Strings.padEnd(Strings.java:129)
       */
      //printOriginalAndResultStrings(null, Strings.padEnd(null, 10, '_'), operation);
      printOriginalAndResultStrings("", Strings.padEnd("", 10, '_'), operation);       
   }

When executed, the above code pads the provided Strings with underscore characters either before or after the provided String depending on which method was called. In both cases, the length of the String was specified as ten. This output is shown in the next screen snapshot.

repeat

A final manipulation technique that Guava's Strings class supports is the ability to easily repeat a given String a specified number of times. This is demonstrated in the next code listing and the corresponding screen snapshot with that code's output. In this example, the provided String is repeated three times.

repeat
   /** Demonstrate Guava Strings.repeat(String,int) method on example Strings. */
   public static void demoRepeat()
   {
      final String operation = "Strings.repeat(String,int)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.repeat("Dustin", 3), operation);
      /*
       * Do NOT call Strings.repeat(String,int) on a null String:
       *    Exception in thread "main" java.lang.NullPointerException
     *         at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
       *         at com.google.common.base.Strings.repeat(Strings.java:153)
       */
      //printOriginalAndResultStrings(null, Strings.repeat(null, 3), operation);
      printOriginalAndResultStrings("", Strings.repeat("", 3), operation);
   }
Wrapping Up

The above examples are simple because Guava's Strings class is simple to use. The complete class containing the demonstration code shown earlier is now listed.

GuavaStrings.java
package dustin.examples;

import com.google.common.base.Strings;
import static java.lang.System.out;

/**
 * Simple demonstration of Guava's Strings class.
 * 
 * @author Dustin
 */
public class GuavaStrings
{
   /**
    * Print to standard output a string message indicating whether the provided
    * String is null or empty or not null or empty. This method uses Guava's
    * Strings.isNullOrEmpty(String) method.
    * 
    * @param string String to be tested for null or empty.
    */
   private static void printStringStatusNullOrEmpty(final String string)
   {
      out.println(  "String '" + string + "' "
                  + (Strings.isNullOrEmpty(string) ? "IS" : "is NOT")
                  + " null or empty.");
   }

   /**
    * Demonstrate Guava Strings.isNullOrEmpty(String) method on some example
    * Strings.
    */
   public static void demoIsNullOrEmpty()
   {
      printHeader("Strings.isNullOrEmpty(String)");
      printStringStatusNullOrEmpty("Dustin");
      printStringStatusNullOrEmpty(null);
      printStringStatusNullOrEmpty("");
   }

   /**
    * Print to standard output a simple message indicating the provided original
    * String and the provided result/output String.
    * 
    * @param originalString Original String.
    * @param resultString Output or result String created by operation.
    * @param operation The operation that acted upon the originalString to create
    *    the resultString.
    */
   private static void printOriginalAndResultStrings(
      final String originalString, final String resultString, final String operation)
   {
      out.println("Passing '" + originalString + "' to " + operation + " produces '" + resultString + "'");
   }

   /** Demonstrate Guava Strings.emptyToNull() method on example Strings. */
   public static void demoEmptyToNull()
   {
      final String operation = "Strings.emptyToNull(String)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.emptyToNull("Dustin"), operation);
      printOriginalAndResultStrings(null, Strings.emptyToNull(null), operation);
      printOriginalAndResultStrings("", Strings.emptyToNull(""), operation);
   }

   /** Demonstrate Guava Strings.nullToEmpty() method on example Strings. */
   public static void demoNullToEmpty()
   {
      final String operation = "Strings.nullToEmpty(String)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.nullToEmpty("Dustin"), operation);
      printOriginalAndResultStrings(null, Strings.nullToEmpty(null), operation);
      printOriginalAndResultStrings("", Strings.nullToEmpty(""), operation);
   }

   /**
    * Demonstrate Guava Strings.padStart(String,int,char) method on example
    * Strings.
    */
   public static void demoPadStart()
   {
      final String operation = "Strings.padStart(String,int,char)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.padStart("Dustin", 10, '_'), operation);
      /* Do NOT call Strings.padStart(String,int,char) on a null String:
       *    Exception in thread "main" java.lang.NullPointerException
     *         at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
     *         at com.google.common.base.Strings.padStart(Strings.java:97)
       */
      //printOriginalAndResultStrings(null, Strings.padStart(null, 10, '_'), operation);
      printOriginalAndResultStrings("", Strings.padStart("", 10, '_'), operation);      
   }

   /**
    * Demonstrate Guava Strings.padEnd(String,int,char) method on example
    * Strings.
    */
   public static void demoPadEnd()
   {
      final String operation = "Strings.padEnd(String,int,char)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.padEnd("Dustin", 10, '_'), operation);
      /*
       * Do NOT call Strings.padEnd(String,int,char) on a null String:
       *    Exception in thread "main" java.lang.NullPointerException
     *         at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
     *         at com.google.common.base.Strings.padEnd(Strings.java:129)
       */
      //printOriginalAndResultStrings(null, Strings.padEnd(null, 10, '_'), operation);
      printOriginalAndResultStrings("", Strings.padEnd("", 10, '_'), operation);       
   }

   /** Demonstrate Guava Strings.repeat(String,int) method on example Strings. */
   public static void demoRepeat()
   {
      final String operation = "Strings.repeat(String,int)";
      printHeader(operation);
      printOriginalAndResultStrings("Dustin", Strings.repeat("Dustin", 3), operation);
      /*
       * Do NOT call Strings.repeat(String,int) on a null String:
       *    Exception in thread "main" java.lang.NullPointerException
     *         at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:187)
       *         at com.google.common.base.Strings.repeat(Strings.java:153)
       */
      //printOriginalAndResultStrings(null, Strings.repeat(null, 3), operation);
      printOriginalAndResultStrings("", Strings.repeat("", 3), operation);
   }

   /**
    * Print a separation header to standard output.
    * 
    * @param headerText Text to be placed in separation header.
    */
   public static void printHeader(final String headerText)
   {
      out.println("\n=========================================================");
      out.println("= " + headerText);
      out.println("=========================================================");
   }

   /**
    * Main function for demonstrating Guava's Strings class.
    * 
    * @param arguments Command-line arguments: none anticipated.
    */
   public static void main(final String[] arguments)
   {
      demoIsNullOrEmpty();
      demoEmptyToNull();
      demoNullToEmpty();
      demoPadStart();
      demoPadEnd();
      demoRepeat();
   }
}

The methods for padding and for repeating Strings do not take kindly to null Strings being passed to them. Indeed, passing a null to these three methods leads to NullPointerExceptions being thrown. Interestingly, these are more examples of Guava using the Preconditions class in its own code.

Conclusion

Many Java libraries and frameworks provide String manipulation functionality is classes with names like StringUtil. Guava's Strings class is one such example and the methods it supplies can make Java manipulation of Strings easier and more concise. Indeed, as I use Guava's Strings's methods, I feel almost like I'm using some of Groovy's GDK String goodness.

No comments: