Of course! The term "Java StringUtils" almost always refers to the StringUtils class from the Apache Commons Lang library. This is an incredibly popular and essential utility library for Java developers.

While Java's standard library (java.lang.String) has many useful methods, the Commons Lang StringUtils class fills in many common gaps, making string manipulation tasks much simpler and less error-prone.
Here’s a comprehensive guide covering everything you need to know.
What is Apache Commons Lang StringUtils?
It's a utility class in the Apache Commons Lang library that provides static methods for performing common operations on String objects that are null-safe.
Key Benefit: It prevents NullPointerException and simplifies code by handling null inputs gracefully.

How to Add it to Your Project
You need to include the Apache Commons Lang dependency in your build file.
For Maven (pom.xml):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.14.0</version> <!-- Check for the latest version -->
</dependency>
For Gradle (build.gradle):
implementation 'org.apache.commons:commons-lang3:3.14.0' // Check for the latest version
Core Categories of Methods
The methods can be grouped into several categories. We'll look at the most useful ones with examples.
A. Null-Safe Checks and Basic Operations
This is the most common reason developers use this library. Standard Java methods like "someString".length() will throw a NullPointerException if the string is null.
StringUtils Method |
Standard Java Equivalent | Description |
|---|---|---|
StringUtils.isEmpty(String str) |
str == null || str.length() == 0 |
Checks if a string is null or empty (). |
StringUtils.isNotEmpty(String str) |
str != null && str.length() > 0 |
Checks if a string is not null and not empty. |
StringUtils.isBlank(String str) |
str == null || str.trim().length() == 0 |
Checks if a string is null, empty, or contains only whitespace. |
StringUtils.isNotBlank(String str) |
str != null && str.trim().length() > 0 |
Checks if a string is not null, not empty, and not whitespace. |
StringUtils.defaultString(String str) |
str != null ? str : "" |
Returns the string itself, or an empty string () if it's null. |
StringUtils.defaultIfEmpty(String str, String defaultStr) |
str != null && !str.isEmpty() ? str : defaultStr |
Returns the string if it's not null or empty, otherwise returns the default. |
Example:

import org.apache.commons.lang3.StringUtils;
public class StringUtilsExample {
public static void main(String[] args) {
String nullString = null;
String emptyString = "";
String blankString = " ";
String normalString = "Hello";
System.out.println("Is nullString empty? " + StringUtils.isEmpty(nullString)); // true
System.out.println("Is emptyString empty? " + StringUtils.isEmpty(emptyString)); // true
System.out.println("Is blankString blank? " + StringUtils.isBlank(blankString)); // true
System.out.println("Is normalString blank? " + StringUtils.isBlank(normalString)); // false
// Standard Java would throw NPE here
// System.out.println(nullString.length());
// StringUtils handles it safely
System.out.println("Length of nullString: " + StringUtils.length(nullString)); // 0
System.out.println("Default for nullString: '" + StringUtils.defaultString(nullString) + "'"); // ''
System.out.println("Default for emptyString: '" + StringUtils.defaultIfEmpty(emptyString, "DEFAULT") + "'"); // 'DEFAULT'
}
}
B. Checking for Substrings
StringUtils Method |
Description |
|---|---|
StringUtils.contains(String str, String searchStr) |
Checks if the string contains the specified substring (case-sensitive). |
StringUtils.containsIgnoreCase(String str, String searchStr) |
Checks if the string contains the substring, ignoring case. |
StringUtils.startsWith(String str, String prefix) |
Checks if the string starts with the given prefix. |
StringUtils.endsWith(String str, String suffix) |
Checks if the string ends with the given suffix. |
Example:
String text = "Apache Commons Lang is great"; System.out.println(StringUtils.contains(text, "Commons")); // true System.out.println(StringUtils.contains(text, "common")); // false System.out.println(StringUtils.containsIgnoreCase(text, "common")); // true System.out.println(StringUtils.startsWith(text, "Apache")); // true System.out.println(StringUtils.endsWith(text, "great")); // true
C. Substring and Manipulation
StringUtils Method |
Description |
|---|---|
StringUtils.substring(String str, int start) |
Gets a substring, starting from the start index. Safe for null input. |
StringUtils.substring(String str, int start, int end) |
Gets a substring from start to end. Safe for null input. |
StringUtils.substringAfter(String str, String separator) |
Gets the substring after the first occurrence of a separator. |
StringUtils.substringBefore(String str, String separator) |
Gets the substring before the first occurrence of a separator. |
StringUtils.substringBetween(String str, String tag) |
Gets the String that is nested in between two tags. |
Example:
String path = "/home/user/documents/report.txt";
System.out.println(StringUtils.substringAfter(path, "/")); // home/user/documents/report.txt
System.out.println(StringUtils.substringBefore(path, "/")); // (empty string)
System.out.println(StringUtils.substringAfterLast(path, "/")); // report.txt
System.out.println(StringUtils.substringBeforeLast(path, "/")); // /home/user/documents
String xmlTag = "<name>John Doe</name>";
System.out.println("Name is: " + StringUtils.substringBetween(xmlTag, "<name>", "</name>")); // John Doe
D. Splitting and Joining
StringUtils Method |
Description |
|---|---|
StringUtils.split(String str, char separatorChar) |
Splits a string into an array of substrings using a single character separator. |
StringUtils.splitByWholeSeparator(String str, String separator) |
Splits a string using a whole string as a separator. |
StringUtils.join(Iterable<?> iterable, String separator) |
Joins the elements of an iterable (like a List or Set) into a single string with a separator. |
StringUtils.join(Object[] array, String separator) |
Joins the elements of an array into a single string with a separator. |
Example:
String csvData = "apple,banana,cherry,date";
String[] fruits = StringUtils.split(csvData, ',');
System.out.println(Arrays.toString(fruits)); // [apple, banana, cherry, date]
List<String> colors = Arrays.asList("red", "green", "blue");
String colorString = StringUtils.join(colors, " - ");
System.out.println(colorString); // red - green - blue
E. Padding and Trimming
StringUtils Method |
Description |
|---|---|
StringUtils.leftPad(String str, int size) |
Pads a String on the left with spaces to a specified length. |
StringUtils.rightPad(String str, int size) |
Pads a String on the right with spaces to a specified length. |
StringUtils.center(String str, int size) |
Centers a String in a larger String of a specified length. |
StringUtils.strip(String str) |
Removes leading and trailing whitespace. null safe. |
StringUtils.stripAll(String[] strs) |
Strips leading and trailing whitespace from each string in an array. |
Example:
String text = "123";
System.out.println("'" + StringUtils.leftPad(text, 5, '0') + "'"); // '00123'
System.out.println("'" + StringUtils.rightPad(text, 8, '-') + "'"); // '123-----'
String messyText = " some text ";
System.out.println("->" + StringUtils.strip(messyText) + "<-"); // ->some text<-
F. Case Conversion
StringUtils Method |
Description |
|---|---|
StringUtils.capitalize(String str) |
Capitalizes a String (changes first character to upper case). |
StringUtils.uncapitalize(String str) |
Uncapitalizes a String (changes first character to lower case). |
StringUtils.swapCase(String str) |
Swaps the case of a String. |
StringUtils.reverse(String str) |
Reverses a String. |
Example:
String name = "java developer"; System.out.println(StringUtils.capitalize(name)); // Java developer System.out.println(StringUtils.swapCase(name)); // JAVA DEVELOPER System.out.println(StringUtils.reverse(name)); // repoleved avaj
Java 8+ Alternatives (The java.util.stream Approach)
With the release of Java 8, many of these tasks can be accomplished using the Stream API and Optional. This can sometimes lead to more expressive, functional-style code.
Example: Checking for null or empty
String myString = null; // Old way (StringUtils) boolean isEmpty = StringUtils.isEmpty(myString); // true // Java 8+ way boolean isEmptyJava8 = Optional.ofNullable(myString).map(String::isEmpty).orElse(true); // true boolean isNotEmptyJava8 = Optional.ofNullable(myString).map(s -> !s.isEmpty()).orElse(false); // false
Example: Joining a List
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Old way (StringUtils)
String joined = StringUtils.join(names, ", "); // "Alice, Bob, Charlie"
// Java 8+ way
String joinedJava8 = String.join(", ", names); // "Alice, Bob, Charlie"
Example: Splitting a String
String data = "a,b,c";
// Old way (StringUtils)
String[] parts = StringUtils.split(data, ','); // ["a", "b", "c"]
// Java 8+ way (using a regex, be careful with special characters)
String[] partsJava8 = data.split(","); // ["a", "b", "c"]
While Java 8+ provides excellent alternatives, StringUtils often remains more concise and readable for many common operations, especially when dealing with null inputs.
Summary: When to Use StringUtils vs. Java Standard Library
| Use Case | Recommendation | Why? |
|---|---|---|
Basic null checks (isEmpty, isBlank) |
StringUtils |
More concise and explicit about null safety. |
| Splitting or Joining strings | StringUtils or Java 8 String.join() |
StringUtils is very flexible. String.join() is great for lists/arrays. |
Substring manipulation (substringAfter, etc.) |
StringUtils |
Offers convenient methods that don't exist in the standard library. |
| Padding and Centering | StringUtils |
These methods are not available in the standard String class. |
Simple operations (length, contains, toUpperCase) |
Standard String class |
No need for an external library. Standard methods are perfectly fine. |
| Code in a modern Java 8+ project | Evaluate both | Consider using Optional and Streams for a more functional style, but don't dismiss StringUtils for its clarity. |
Conclusion: The Apache Commons Lang StringUtils is a timeless, powerful, and highly recommended tool for any Java project. It improves code robustness by handling null values and provides a rich set of utility methods that simplify common string operations.
