Published on Sat Mar 15 2025 10:00:00 GMT+0000 (Coordinated Universal Time) by Purusothaman Ramanujam
String Utilities in Apache Commons Lang
Introduction
String manipulation is one of the most common tasks in Java development. While Java’s String class provides basic functionality, Apache Commons Lang’s StringUtils offers a comprehensive set of utilities that make string operations more convenient, null-safe, and powerful.
In this comprehensive guide, you’ll learn how to use StringUtils effectively with detailed examples and real-world use cases.
Adding Apache Commons Lang to Your Project
Maven Dependency
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.13.0</version></dependency>Gradle Dependency
implementation 'org.apache.commons:commons-lang3:3.13.0'Basic String Operations
Null-Safe Operations
One of the biggest advantages of StringUtils is its null-safe operations:
import org.apache.commons.lang3.StringUtils;
public class StringUtilsBasics { public static void main(String[] args) { String str1 = "Hello World"; String str2 = null; String str3 = ""; String str4 = " ";
// Null-safe length System.out.println(StringUtils.length(str1)); // 11 System.out.println(StringUtils.length(str2)); // 0 (not null pointer exception!)
// Null-safe isEmpty System.out.println(StringUtils.isEmpty(str1)); // false System.out.println(StringUtils.isEmpty(str2)); // true System.out.println(StringUtils.isEmpty(str3)); // true
// Null-safe isBlank (checks for whitespace too) System.out.println(StringUtils.isBlank(str1)); // false System.out.println(StringUtils.isBlank(str2)); // true System.out.println(StringUtils.isBlank(str3)); // true System.out.println(StringUtils.isBlank(str4)); // true }}Trimming and Cleaning
public class StringCleaning { public static void main(String[] args) { String dirty = " Hello World \n\t";
// Basic trim System.out.println(StringUtils.trim(dirty)); // "Hello World"
// Trim to null (returns null if result is empty) System.out.println(StringUtils.trimToNull(" ")); // null System.out.println(StringUtils.trimToEmpty(" ")); // ""
// Clean whitespace System.out.println(StringUtils.deleteWhitespace("Hello World")); // "HelloWorld"
// Normalize whitespace System.out.println(StringUtils.normalizeSpace(" Hello World ")); // "Hello World" }}String Validation
Checking String Content
public class StringValidation { public static void main(String[] args) { String text = "Hello123"; String alpha = "HelloWorld"; String numeric = "12345"; String mixed = "Hello123World";
// Check if string contains only letters System.out.println(StringUtils.isAlpha(text)); // false System.out.println(StringUtils.isAlpha(alpha)); // true
// Check if string contains only digits System.out.println(StringUtils.isNumeric(text)); // false System.out.println(StringUtils.isNumeric(numeric)); // true
// Check if string is alphanumeric System.out.println(StringUtils.isAlphanumeric(mixed)); // true
// Check if string is all lowercase/uppercase System.out.println(StringUtils.isAllLowerCase("hello")); // true System.out.println(StringUtils.isAllUpperCase("HELLO")); // true
// Check if string starts/ends with (case-insensitive) System.out.println(StringUtils.startsWithIgnoreCase("Hello", "he")); // true System.out.println(StringUtils.endsWithIgnoreCase("Hello", "LO")); // true }}String Transformation
Case Manipulation
public class StringTransformation { public static void main(String[] args) { String text = "hello world";
// Capitalize first letter System.out.println(StringUtils.capitalize(text)); // "Hello world"
// Capitalize all words System.out.println(StringUtils.capitalizeFully(text)); // "Hello World"
// Uncapitalize System.out.println(StringUtils.uncapitalize("Hello World")); // "hello World"
// Swap case System.out.println(StringUtils.swapCase("Hello World")); // "hELLO wORLD"
// Convert to camel case System.out.println(StringUtils.capitalizeFully("hello world", ' ')); // "Hello World" }}String Replacement
public class StringReplacement { public static void main(String[] args) { String text = "Hello World Hello";
// Replace first occurrence System.out.println(StringUtils.replaceOnce(text, "Hello", "Hi")); // "Hi World Hello"
// Replace all occurrences System.out.println(StringUtils.replace(text, "Hello", "Hi")); // "Hi World Hi"
// Replace with case-insensitive matching System.out.println(StringUtils.replaceIgnoreCase(text, "hello", "Hi")); // "Hi World Hi"
// Replace multiple patterns String[] searchList = {"Hello", "World"}; String[] replacementList = {"Hi", "Earth"}; System.out.println(StringUtils.replaceEach(text, searchList, replacementList)); // "Hi Earth Hi" }}String Comparison
Advanced Comparison Methods
public class StringComparison { public static void main(String[] args) { String str1 = "Hello"; String str2 = "hello"; String str3 = "HELLO";
// Case-insensitive comparison System.out.println(StringUtils.equalsIgnoreCase(str1, str2)); // true
// Compare with null safety System.out.println(StringUtils.equals(str1, null)); // false System.out.println(StringUtils.equals(null, null)); // true
// Get difference between strings System.out.println(StringUtils.difference("Hello", "Hello World")); // " World"
// Get common prefix System.out.println(StringUtils.getCommonPrefix("Hello", "Help")); // "Hel"
// Get common suffix System.out.println(StringUtils.getCommonSuffix("Hello", "World")); // "" System.out.println(StringUtils.getCommonSuffix("Testing", "String")); // "ing" }}String Padding and Alignment
Padding Operations
public class StringPadding { public static void main(String[] args) { String text = "Hello";
// Left pad System.out.println(StringUtils.leftPad(text, 10)); // " Hello" System.out.println(StringUtils.leftPad(text, 10, '*')); // "*****Hello"
// Right pad System.out.println(StringUtils.rightPad(text, 10)); // "Hello " System.out.println(StringUtils.rightPad(text, 10, '*')); // "Hello*****"
// Center pad System.out.println(StringUtils.center(text, 10)); // " Hello " System.out.println(StringUtils.center(text, 10, '*')); // "**Hello***"
// Repeat string System.out.println(StringUtils.repeat("Hello", 3)); // "HelloHelloHello" System.out.println(StringUtils.repeat("Hello", " ", 3)); // "Hello Hello Hello" }}String Splitting and Joining
Advanced Splitting
import java.util.Arrays;
public class StringSplitting { public static void main(String[] args) { String text = "Hello,World,Java,Programming";
// Split by delimiter String[] parts = StringUtils.split(text, ","); System.out.println(Arrays.toString(parts)); // [Hello, World, Java, Programming]
// Split with limit String[] limited = StringUtils.split(text, ",", 2); System.out.println(Arrays.toString(limited)); // [Hello, World,Java,Programming]
// Split by whitespace String whitespaceText = "Hello World Java"; String[] words = StringUtils.split(whitespaceText); System.out.println(Arrays.toString(words)); // [Hello, World, Java]
// Split by character type String mixed = "Hello123World456Java"; String[] byType = StringUtils.splitByCharacterType(mixed); System.out.println(Arrays.toString(byType)); // [Hello, 123, World, 456, Java] }}String Joining
public class StringJoining { public static void main(String[] args) { String[] words = {"Hello", "World", "Java"};
// Join with delimiter System.out.println(StringUtils.join(words, " ")); // "Hello World Java" System.out.println(StringUtils.join(words, ",")); // "Hello,World,Java"
// Join with custom separator and prefix/suffix System.out.println(StringUtils.join(words, ",")); // "Hello,World,Java"
// Join with different start/end indices System.out.println(StringUtils.join(words, " ", 1, 3)); // "World Java" }}String Abbreviation and Truncation
Abbreviation Methods
public class StringAbbreviation { public static void main(String[] args) { String longText = "This is a very long text that needs abbreviation";
// Abbreviate with ellipsis System.out.println(StringUtils.abbreviate(longText, 20)); // "This is a very..."
// Abbreviate with custom ellipsis System.out.println(StringUtils.abbreviate(longText, "***", 20)); // "This is a very***"
// Abbreviate middle System.out.println(StringUtils.abbreviateMiddle(longText, "...", 20)); // "This is a...ation"
// Truncate without ellipsis System.out.println(StringUtils.truncate(longText, 20)); // "This is a very long" }}Real-World Examples
Email Validation
public class EmailValidation { public static boolean isValidEmail(String email) { if (StringUtils.isBlank(email)) { return false; }
// Basic email validation String trimmed = StringUtils.trim(email); return trimmed.contains("@") && !StringUtils.startsWith(trimmed, "@") && !StringUtils.endsWith(trimmed, "@") && trimmed.length() > 5; }
public static void main(String[] args) { System.out.println(isValidEmail("user@example.com")); // true System.out.println(isValidEmail(" user@example.com ")); // true System.out.println(isValidEmail("")); // false System.out.println(isValidEmail(null)); // false System.out.println(isValidEmail("@example.com")); // false }}Text Processing
public class TextProcessor { public static String cleanAndFormatText(String input) { if (StringUtils.isBlank(input)) { return ""; }
// Normalize whitespace String normalized = StringUtils.normalizeSpace(input);
// Capitalize first letter of each word String capitalized = StringUtils.capitalizeFully(normalized);
// Remove extra punctuation String cleaned = StringUtils.replaceEach(capitalized, new String[]{",,", "..", "!!"}, new String[]{",", ".", "!"});
return cleaned; }
public static void main(String[] args) { String dirtyText = " hello world,, java!! "; System.out.println(cleanAndFormatText(dirtyText)); // "Hello World, Java!" }}Performance Considerations
When to Use StringUtils vs Standard String Methods
public class PerformanceComparison { public static void main(String[] args) { // Use StringUtils for null-safe operations StringUtils.isBlank(null); // Safe
// Use standard String methods for simple operations "Hello".toUpperCase(); // More efficient than StringUtils.upperCase()
// Use StringUtils for complex operations StringUtils.capitalizeFully("hello world"); // More convenient than manual implementation }}Best Practices
- Always use null-safe methods when dealing with user input or external data
- Prefer
isBlank()overisEmpty()for checking empty strings (includes whitespace) - Use
StringUtilsfor complex operations and standard String methods for simple ones - Consider performance for frequently called methods in loops
- Read the documentation for edge cases and additional methods
Common Pitfalls
public class CommonPitfalls { public static void main(String[] args) { // Pitfall 1: Not checking for null String str = null; // str.length(); // Throws NullPointerException StringUtils.length(str); // Safe, returns 0
// Pitfall 2: Using isEmpty instead of isBlank String whitespace = " "; // whitespace.isEmpty(); // false (not what you want) StringUtils.isBlank(whitespace); // true (what you want)
// Pitfall 3: Not handling empty results String result = StringUtils.trimToNull(" "); if (result == null) { // Handle null case } }}Conclusion
StringUtils from Apache Commons Lang provides a robust set of utilities that make string manipulation safer, more convenient, and more powerful. By understanding these methods and their proper usage, you can write cleaner, more maintainable code that handles edge cases gracefully.
The key benefits include:
- Null safety - No more NullPointerExceptions
- Convenience - Less boilerplate code
- Consistency - Standardized string operations
- Performance - Optimized implementations
Start incorporating StringUtils into your projects and see how it simplifies your string manipulation code!
Resources
Written by Purusothaman Ramanujam
← Back to blog