StringUtils is a utility class of the Apache Commons Lang library that helps us manipulate/process the strings efficiently. It offers a variety of advanced string manipulation methods that don’t exist in the standard String class. Also, most of these methods are null-safe which makes the StringUtils class superior to the standard String class. Using the practical implementation of these methods, we will see how to use the StringUtils class in Java.
How to Use StringUtils in Java
Apache Commons Lang is a third-party library that must be added/imported into your Java project to use any of its classes like “StringUtils”. For this purpose, you can add the “Apache Commons Lang” dependency either in your Maven or Gradle projects.
Adding Apache Commons Lang Dependency in Maven Project
When you create a Maven project, a “pom.xml” file is also created inside it by default. Locate the “pom.xml” file in your Maven project, open it, and paste the following dependency in it:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version>
</dependency>
Once the dependency is successfully added to your project, include the following import statement in your Java class:
import org.apache.commons.lang3.StringUtils;
Now you are all set to use any method of the StringUtils class.
Adding Apache Commons Lang Dependency in Gradle Project
Alternatively, you can create a Gradle project and add the below-stated dependency in its “build.gradle” file to use/access the StringUtils class of Apache Commons Lang:
dependencies {
implementation 'org.apache.commons:commons-lang3:3.14.0'
}
After adding the respective dependency to your Gradle project, use the following import statement at the start of the Java class:
import org.apache.commons.lang3.StringUtils;
This statement allows you to use any method of the StringUtils class without any hassles.
Useful Methods of StringUtils Class
The StringUtils class offers a wide range of utility methods that you can use in your Java application to perform different String Manipulation Tasks. These methods allow us to perform case-insensitive comparisons, null-safe string manipulation, efficient string formatting, and much more. We have classified these methods into different categories as illustrated below:
String Comparison
The table below shows different methods of the StringUtils class that compare the given strings in null safe manner:
Method Name | Description | Syntax |
---|---|---|
equals() | Checks the string equality and returns a Boolean true or false. | StringUtils.equals(str1, str2); |
equalsIgnoreCase() | Checks strings equality regardless of letter case. | StringUtils.equalsIgnoreCase(str1, str2); |
equalsAny() | Accepts multiple strings as parameters. It compares the first string with the rest of the strings and retrieves true if it matches/corresponds with any of the provided strings. | StringUtils.equalsAny(str1, str2, …, strN); |
equalsAnyIgnoreCase() | It works the same as the equalsAny() method; the only difference is it performs case-insensitive comparisons. | StringUtils.equalsAnyIgnoreCase(str1, str2, …, strN); |
compare() | It accepts two strings and compares them character by character. It returns an integer, 0 means both strings are equal. Else not equal. | StringUtils.compare(str1, str2); |
compareIgnoreCase() | It performs case-insensitive comparisons. | StringUtils.compareIgnoreCase(str1, str2); |
Example: Comparing Strings Using StringUtils Methods
In this example, we declare and initialize a couple of strings. After this, we apply the above-mentioned string comparison methods to the provided strings:
import org.apache.commons.lang3.StringUtils;
public class ExampleClass {
public static void main(String[] args) {
String domainName = "JavaBeat";
String domainName1 = "javabeat";
System.out.println("Result of equals Method ==> " + StringUtils.equals(domainName, domainName1));
System.out.println("Result of equalsIgnoreCase Method ==> " + StringUtils.equalsIgnoreCase(domainName, domainName1));
System.out.println("Result of equalsAny Method ==> " + StringUtils.equalsAny(domainName, domainName1));
System.out.println("Result of equalsAnyIgnoreCase Method ==> " + StringUtils.equalsAnyIgnoreCase(domainName, domainName1));
System.out.println("Result of compare Method ==> " + StringUtils.compare(domainName, domainName1));
System.out.println("Result of compareIgnoreCase Method ==> " + StringUtils.compareIgnoreCase(domainName, domainName1));
}
}
In this code,
- We create two strings: “JavaBeat”, “javabeat”, and store them in variables “domainName” and “domainName1”, respectively.
- After this, we use the “equals()”, “equalsAny()”, and “compare()” methods to perform case-sensitive string comparison.
- Also, we execute the IgnoreCase variants of these methods to do the case-insensitive comparisons.
The following snippet shows the outcome of each method:
Check the Characters in a String
The StringUtils class offers several methods to check if a string contains numbers, whitespaces, Unicode characters, etc. The below table demonstrates these methods with description and syntax:
Method Name | Description | Syntax |
---|---|---|
isNumeric() | Accepts a string and retrieves true if the given string is numeric. | StringUtils.isNumeric(inputString); |
isNumericSpace() | Accepts a string and retrieves true if the given string is numeric and contains some whitespaces. | StringUtils.isNumericSpace(inputString); |
isAlpha() | It accepts a string as input and retrieves true if it contains only Unicode characters. If the specified string is null/empty, then a boolean false will be retrieved. | StringUtils.isAlpha(inputString); |
isAsciiPrintable() | It checks if the provided string contains ASCII characters and is printable. If yes it retries true. | StringUtils.isAsciiPrintable(inputString); |
Example: Check the Characters in a String Using StringUtils Methods
The given code block creates a numeric string and applies the above-mentioned methods to show how they work:
import org.apache.commons.lang3.StringUtils;
public class ExampleClass {
public static void main(String[] args) {
String numString = "123910";
System.out.println("Result of isNumeric Method ==> " + StringUtils.isNumeric(numString));
System.out.println("Result of isNumericSpace Method ==> " + StringUtils.isNumericSpace(numString));
System.out.println("Result of isAlpha Method ==> " + StringUtils.isAlpha(numString));
System.out.println("Result of isAsciiPrintable Method ==> " + StringUtils.isAsciiPrintable(numString));
}
}
The isAlpha() retrieves “false” because the provided string doesn’t contain the Unicode characters. While the other three methods return “true” as shown in the below output:
Check Empty/Null Strings
The StringUtils class provides a couple of utility methods that check the null and blank strings. Also, it offers a method to check if the targeted string contains whitespaces or not. In the below table, these methods are demonstrated alongside their basic syntaxes:
Method Name | Description | Syntax |
---|---|---|
isEmpty() | It retrieves true if the provided string is empty(zero length/character) or null. | StringUtils.isEmpty(inputString); |
isBlank() | It retrieves true if the string is empty, includes whitespaces only, or is null. | StringUtils.isBlank(inputString); |
isWhitespace() | It retrieves true if the input string contains whitespaces, or doesn’t contain any character at all. It retrieves false if the given string is null. | StringUtils.isWhitespace(inputString); |
Example: Check the Characters in a String Using StringUtils Methods
In the below code, we invoke the isEmpty(), isBlank(), and isWhitespace() methods on a string that contains a couple of whitespaces only:
import org.apache.commons.lang3.StringUtils;
public class ExampleClass {
public static void main(String[] args) {
String numString = " ";
System.out.println("Result of isEmpty Method ==> " + StringUtils.isEmpty(numString));
System.out.println("Result of isBlank Method ==> " + StringUtils.isBlank(numString));
System.out.println("Result of isWhitespace Method ==> " + StringUtils.isWhitespace(numString));
}
}
As expected, the isEmpty() method returns “false” while the other two methods retrieve “true”:
Check Substrings
Substring extraction is a widely used concept that can be achieved using the below-illustrated utility methods of the StringUtils class:
Method Name | Description | Syntax |
---|---|---|
substring() | It extracts a substring from the given string based on the specified start and end indexes. | StringUtils.substring(String str, int startIndex, int endIndex); |
substringBefore() | It retrieves a substring that appears before the first occurrence of the separator. | StringUtils.substringBefore(String str, String separator); |
substringAfter() | It retrieves a substring that appears after the first occurrence/instance of the separator/delimiter. | StringUtils.substringAfter(String str, String separator); |
substringBetween() | It retrieves the first occurrence of a substring that is nested between two strings. | StringUtils.substringBetween(String str, String stringOpen, String stringClose); |
left() | It retrieves the specified characters from the leftmost of the given string. | StringUtils.left(String str, int charLen); |
mid() | It retrieves a substring from the mid of the given string based on the specified index position and length. | StringUtils.mid(String, int position, int length); |
right() | It returns the selected characters from the rightmost of the given string. | StringUtils.right(String str, int charLen); |
Example: Get Substrings of a String Using StringUtils Methods
Let’s use the above-described methods to witness their functionality:
import org.apache.commons.lang3.StringUtils;
public class ExampleClass {
public static void main(String[] args) {
String givenString = "Welcome to javabeat.net";
System.out.println("Substring Using substring Method ==> " + StringUtils.substring(givenString, 11, 19));
System.out.println("Substring Using substringBefore Method ==> " + StringUtils.substringBefore(givenString, " "));
System.out.println("Substring Using substringAfter Method ==> " + StringUtils.substringAfter(givenString, " "));
System.out.println("Substring Using substringBetween Method ==> " + StringUtils.substringBetween(givenString, "to", "beat"));
System.out.println("Substring Using left Method ==> " + StringUtils.left(givenString, 3));
System.out.println("Substring Using right Method ==> " + StringUtils.right(givenString, 3));
System.out.println("Substring Using mid Method ==> " + StringUtils.mid(givenString, 11, 4));
}
}
In the above code:
- The substring() method extracts a substring from the 11th index to the 19th index.
- The substringBefore() extracts a substring prior to the first occurrence of the delimiter, i.e., whitespace “ ”.
- The substringAfter() retrieves a substring after the first occurrence/existence of the delimiter, i.e., whitespace “ ”.
- The substringBetween() extracts a substring between the first occurrence of “to” to the first occurrence of “beat”.
- The left() and right() methods extract the first three(leftmost) and last three(rightmost) characters from the given string, respectively.
- Finally, the mid() method extracts and retrieves the four characters from the 11th index onwards.
Check the Index of Strings
StringUtils class provides a wide range of index functions. These functions help us get/retrieve the specific index of the specified search sequence from the provided string/text.
Method Name | Description | Syntax |
---|---|---|
indexOf() | This method finds and retrieves the first index of the specified CharSequence. | StringUtils.indexOf(String str, String charSeq); |
lastIndexOf() | It retrieves the last index of the given charSequence. | StringUtils.lastIndexOf(String str, CharSeq str); |
indexOfAny() | It retrieves the index of any character from the provided set of characters. | StringUtils.indexOfAny(String str, charSeq str, CharSeq str, …); |
lastIndexOfAny() | It finds and retrieves the last/latest index of any substring in a set of possible substrings. | StringUtils.lastIndexOfAny(String str, CharSeq str); |
contains() | It checks if the given string contains the specified charSequence. | StringUtils.contains(String str, CharSeq str); |
containsOnly() | It retrieves true if the CharSequence contains only specific characters. | StringUtils.containsOnly(CharSequence str, String str); |
containsNone() | It retrieves true if the targeted string doesn’t contain the specified substring/characters. | StringUtils.containsNone(CharSequence str, String str); |
containsAny() | It retrieves true if the targeted string contains any of the specified substrings. | StringUtils.containsAny(CharSequence str, String str1, String str2, …); |
Example: Check Index of String/Character Using StringUtils Methods
Now we will show you how you can implement the above methods to check the index of a specific character/substring:
import org.apache.commons.lang3.StringUtils;
public class ExampleClass {
public static void main(String[] args) {
String givenString = "JavaBeat.net";
System.out.println("Result of indexOf Method ==> " + StringUtils.indexOf(givenString, "B"));
System.out.println("Result of lastIndexOf Method ==> " + StringUtils.lastIndexOf(givenString, "a"));
System.out.println("Result of indexOfAny Method ==> " + StringUtils.indexOfAny(givenString, "b", "j", "v", "n"));
System.out.println("Result of lastIndexOfAny Method ==> " + StringUtils.lastIndexOfAny(givenString, "a", "n"));
System.out.println("Result of contains Method ==> " + StringUtils.contains(givenString, "eat"));
System.out.println("Result of containsOnly Method ==> " + StringUtils.containsOnly(givenString, "JavaBeat.net"));
System.out.println("Result of containsNone Method ==> " + StringUtils.containsNone(givenString, "com"));
System.out.println("Result of containsAny Method ==> " + StringUtils.containsAny(givenString, "Beat"));
}
}
In this example,
- First, we invoke the indexOf(), lastIndexOf() methods on the given string to get the first and last index of specified characters.
- Up next, we execute the “indexOfAny()” and “lastIndexOfAny()” to retrieve the first and last index of any provided character sequences, respectively.
- After this, we use the contains() to check if the specified string contains a substring “eat”. Also, we invoke the containsOnly() to check if the string contains only the string “JavaBeat.net”.
- Next, we invoke the containsNone() to ensure that the specified string doesn’t contain a substring “com”.
- Finally, we use the containsAny() method to check if the input string contains a substring “Beat”.
String Manipulation
The following methods of the StringUtils class are used to perform different string manipulation operations, such as joining multiple strings, trimming a string, replacing a substring with another substring, etc.
Method Name | Description | Syntax |
---|---|---|
startsWith() | Checks if a string starts with the specified prefix/character. If so, it retrieves true. | StringUtils.startsWith(CharSeq str, CharSeq prefix); |
endsWith() | This method checks if a string ends with a particular suffix/character. If so, it retrieves true. | StringUtils.endsWith(CharSeq str, CharSeq suffix); |
trim() or strip() | It removes/trims the control characters from the start/left and end/right of the given string. | StringUtils.trim(String str); |
split() | This method splits/breaks the given text into an array, using a blank space as a delimiter. | StringUtils.split(String str); |
join() | Accepts multiple strings as parameters and combines them. | StringUtils.join(String str1, str2, str3, …); |
remove() | Takes a specific string as input and removes all of its occurrences from the source string. | StringUtils.remove(String str, String remStr); |
replace() | It replaces all the occurrences of a specific substring with another substring. | StringUtils.replace(String str, String replaceStr, String replaceWith); |
chomp() or chop() | It removes one new line from the end of the specified String (if it’s there). Otherwise, it leaves the specified string as it is. The new line character can be “\n”,”\r”, or “\r\n”. | StringUtils.chomp(String str); |
leftPad() or rightPad() | Left pads or right pads the given string with the specified number of whitespaces, respectively. | StringUtils.leftPad(String str, int len);orStringUtils.rightPad(String str, int len); |
reverse() | It reverses the given string (i.e., from left-to-right to right-to-left). | StringUtils.reverse(String str); |
Example: Performing String Manipulation Using StringUtils Methods
The below code snippet utilizes the above-stated methods to perform different string manipulation operations:
import org.apache.commons.lang3.StringUtils;
public class ExampleClass {
public static void main(String[] args) {
String givenString = " JavaBeat.net ";
System.out.println("The String starts with a Whitespace? ==> " + StringUtils.startsWith(givenString, " "));
System.out.println("The String ends with a Whitespace? ==> " + StringUtils.endsWith(givenString, " "));
System.out.println("Whitespaces are trimmed from the start and end of given string ==> " + StringUtils.trim(givenString));
System.out.println("The Given string is joined with Let's learn Java ==> " + StringUtils.join(givenString, "Let's Learn Java"));
System.out.println(".net is removed from the string ==> " + StringUtils.remove(givenString, ".net"));
System.out.println("Java is replaced with Python ==> " + StringUtils.replace(givenString, "Java", "Python"));
System.out.println("The chomp Method Removes 1 newline from the string ==> " + StringUtils.chomp("JavaBeat\n"));
System.out.println("Left pad the given string with two whitespaces ==> " + StringUtils.leftPad(givenString, 2));
System.out.println("Reverse the Given string ==> " + StringUtils.reverse(givenString));
}
}
In the above code,
- First, we invoke the startsWith() and endsWith() methods to check if the given string starts and ends with a white space.
- Up next, we trim the unwanted whitespaces from the specified string using the “trim()” method.
- After this, we invoke the join() method on the specified string to join it with a new string “Let’s learn Java”.
- Next, we use the “remove()” and replace() methods to remove and replace the unwanted string with the desired strings, respectively.
- After this, we chomp a new line from the given string. Also, we left-pad the given string with a couple of whitespaces.
- Finally, we reverse the given string using the reverse() method:
Case Conversion
Java is a case-sensitive language, therefore, it offers several case-conversion methods to convert the strings of different cases into a single case. Once the strings are converted into the same case, you can perform any string operation, without worrying about the letter case:
Method Name | Description | Syntax |
---|---|---|
upperCase() | Converts all letters of the selected string into uppercase. | StringUtils.upperCase(String str); |
lowerCase() | Transforms all characters of the given string into lowercase. | StringUtils.lowerCase(String str); |
swapCase() | Swap the lowercase to uppercase or vice versa. | StringUtils.swapCase(String str); |
capitalize() | It converts the first character into uppercase. | StringUtils.capitalize(String str); |
uncapitalize() | Uncapatilize/convert the first character into lowercase. | StringUtils.uncapitalize(String str); |
Example: Convert Case of a String Using StringUtils Methods
This section discusses different methods to convert the letter case of a string from one convention to another:
import org.apache.commons.lang3.StringUtils;
public class ExampleClass {
public static void main(String[] args) {
String givenString = "Welcome to javabeat.net";
System.out.println("Result of Uppercase Method ==> " + StringUtils.upperCase(givenString));
System.out.println("Result of lowerCase Method ==> " + StringUtils.lowerCase(givenString));
System.out.println("Result of swapCase Method ==> " + StringUtils.swapCase(givenString));
System.out.println("Result of capitalize Method ==> " + StringUtils.capitalize(givenString));
System.out.println("Result of uncapitalize Method ==> " + StringUtils.uncapitalize(givenString));
}
}
In the above code,
- First, the uppercase() and lowercase() methods are invoked to convert all letters into upper and lowercase, respectively.
- After this, we employ the swapCase() method to transform lower-to-upper and upper-to-lower cases.
- Finally, we capitalize and uncapitalize the given string, as shown below:
Other Useful StringUtils Methods
The below table illustrates some lesser-known yet very useful StringUtils methods:
Method Name | Description | Syntax |
---|---|---|
appendIfMissing() | It appends a suffix to the end of the given string if the string doesn’t already end with any of the specified suffixes. | StringUtils.appendIfMissing(String str, CharSequence prefix, CharSequence prefix, …); |
prependIfMissing() | It prepends a prefix to the beginning/left of the given string if the string doesn’t already begin with any of the specified prefixes. | StringUtils.prependIfMissing(String str, CharSequence prefix, CharSequence prefix, …); |
center() | Centers the given string with white spaces (according to the specified size). | StringUtils.center(String str, int size); |
repeat() | It repeats the given string according to the specified number of repetitions. | StringUtils.repeat(String str, int repeatNum); |
countMatches() | It checks and counts how many times the specified substring occurs in the source string. | StringUtils.countMatches(String str, String substring); |
defaultString() | Retrieves the passed string as it is. | StringUtils.defaultString(String str); |
rotate() | It rotates the given string according to the specified shifts. | StringUtils.rotate(String str, int shifts); |
abbreviate() | Abbreviates the given string according to the specified width. | StringUtils.abbreviate(String str, int maxWidth); |
difference() | Retrieves the difference between two given strings. The returned string represents the portion of the second string, which differs from the first one. | StringUtils.difference(String str1, String str2); |
That’s all about the StringUtils class in Java.
Conclusion
To Use the StringUtils class in Java, first, add its corresponding Apache Commons dependency in a “pom.xml” file of your maven project. After this, you can import the StringUtils class in your Java application and use any of its methods to manipulate the strings efficiently. The StringUtils class offers some advanced string/text handling methods that are not available/accessible in the standard String class. These methods allow you to perform case-insensitive comparisons, null-safe searching, and much more. In this guide, we have shortlisted the most used StringUtils method and discussed them with appropriate examples.