Break

10 Simple String Utility Methods for Java Developer

String operations are common to all kind of programming. Java has many in built operations supported by String class. String functions in java include substring, split, trim and more. However there are few more things we do on a regular basis and can be reused. There are few functions which I observed commonly used and may be helpful to keep handy as StringUtil class with static methods.

Exceptions class provides a printStackTrace() method which directly prints the Stack Trace to the console. Sometimes you may need to take stack trace to a String variable and use it (e.g. logging using logger), or doing processing on the trace e.g. eclipse shows stack trace and links it to the file and line number. Below is a simple piece of code which demonstrates how we can capture the stack trace inside as String variable. This example utilizes the StringWriter class to convert the stream content to a String.

This is another simple Java String utility method, which can be used to merge two arrays of String values. This takes care of eliminating the duplicates and also does null checking. If you are dealing with multiple String arrays then it could be a useful method.

This is another simple but useful Java String Utility/Util method, which can be used to trim all String values in an array of String. This takes care of null checking while doing trim.
java.lang.String class contains the trim method which can be used to trim a string from left and right both sides. So for example if you have a string [" This is a String "] then calling a trim() method on this string will convert it to ["This is a String"].

This method can be used to unquote a string value. This method takes care of single and double quotes both along with handling the null string. It returns the string as it is when the string is not quoted.

Exact file name extraction is required many times, when dealing with files. Below is a String utility method, which can be used to extract the exact file name from a absolute path. It uses the File.separatorChar which should take care of all platforms.

/**
* This method extracts the file name from absolute path of file
* As an example :
*

*
*

* For an input "c:\myDir\MyFile.java"
* The output will be : "MyFile"
*

A better and simpler/improved version of same method is suggested by one of readers and the code looks like this.

/**
* This method is used to split the given string into different tokens at
* the occurrence of specified delimiter
* An example :
* "abcdzefghizlmnop" and using a delimiter "z"
* would give following output
* "abcd" "efghi" "lmnop"
*
* @param str The string that needs to be broken
* @param delimeter The delimiter used to break the string
* @return a string array
*/
public static String[] getTokensArray(String str, String delimeter) {
if (str != null) {
return str.split(delimeter);
}
return null;
}

Another variation for same method is for getting a java.util.List instead of array of objects. This can be easily done using small change to above method

/**
* This method is used to split the given string into different tokens at
* the occurrence of specified delimiter
* An example :
* "abcdzefghizlmnop" and using a delimiter "z"
* would give following output
* "abcd" "efghi" "lmnop"
*
* @param str The string that needs to be broken
* @param delimeter The delimiter used to break the string
* @return a instance of java.util.List with each token as one item in list
*/
public static List getTokensList(String str, String delimeter) {
if (str != null) {
return Arrays.asList(str.split(delimeter));
}
return new ArrayList();
}

The java.lang.String class default implementation has startsWith and endsWith() methods which perform case sensitive comparison, Below are two functions, which can be used to do the same startsWith/endsWith check ignoring the case.

This method can be used to create a set of unique string values from a string which has tokens separated by some separator. This is very useful method when you get the input as comma or space separated string, which has to be converted to set of values when dealing with each value individually and avoiding duplicates.
The code is using StringTokenizer for separating the tokens, so single or multiple separators can be used.

There are times when we don't want to deal with null String values, in such cases below utility method can be utilized. This method return a empty string value in case the string value is null. Same argument of extra method call may come up for this as well, but you may save unwanted NullPointerException in your application by using such a method.
I have found this useful at places where we are displaying a field value on user interface and want to mask the null values with empty string.