Everything Java

← Back to blog

Published on Tue Mar 04 2025 10:00:00 GMT+0000 (Coordinated Universal Time) by Purusothaman Ramanujam

Useful Utilities from Apache Commons Lang - Complete Overview

Introduction

Java’s standard library is powerful, but sometimes you need more convenient utilities for everyday tasks. Apache Commons Lang is a popular library that extends the core Java classes with extra methods for string manipulation, object handling, number utilities, random generation, and system utilities.

This comprehensive overview introduces you to the most useful features of Apache Commons Lang and provides links to detailed guides for each utility category.

What is Apache Commons Lang?

Apache Commons Lang is part of the larger Apache Commons project. It provides helper utilities for the java.lang API, including:

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'

String Utilities (StringUtils)

String manipulation is one of the most common tasks in Java development. StringUtils provides null-safe operations that make string handling more convenient and robust.

Key Features:

Quick Example:

import org.apache.commons.lang3.StringUtils;
// Null-safe operations
StringUtils.isBlank(null); // true
StringUtils.isBlank(" "); // true
StringUtils.isBlank("Hello"); // false
// String transformation
StringUtils.capitalize("hello world"); // "Hello world"
StringUtils.capitalizeFully("hello world"); // "Hello World"
// String validation
StringUtils.isAlpha("Hello"); // true
StringUtils.isNumeric("123"); // true
StringUtils.isAlphanumeric("Hello123"); // true

πŸ“– Read the complete String Utilities guide β†’

Number Utilities (NumberUtils)

Working with numbers in Java can be tricky, especially when dealing with parsing, validation, and conversion between different numeric types. NumberUtils provides comprehensive utilities for number operations.

Key Features:

Quick Example:

import org.apache.commons.lang3.math.NumberUtils;
// Null-safe operations
NumberUtils.max(10, null); // 10
NumberUtils.min(null, 20); // 20
// Number parsing with defaults
NumberUtils.toInt("123", -1); // 123
NumberUtils.toInt("abc", -1); // -1
// Number validation
NumberUtils.isCreatable("123.45"); // true
NumberUtils.isDigits("123"); // true
NumberUtils.isParsable("123.45"); // true
// Mathematical operations
NumberUtils.gcd(12, 18); // 6
NumberUtils.lcm(12, 18); // 36
NumberUtils.factorial(5); // 120

πŸ“– Read the complete Number Utilities guide β†’

Random Utilities (RandomStringUtils)

Generating random data is a common requirement in Java applications, whether for testing, creating unique identifiers, or generating sample data. RandomStringUtils provides flexible random string generation.

Key Features:

Quick Example:

import org.apache.commons.lang3.RandomStringUtils;
// Basic random generation
RandomStringUtils.randomAlphanumeric(10); // "a8B3kLm2"
RandomStringUtils.randomAlphabetic(8); // "HelloWor"
RandomStringUtils.randomNumeric(6); // "123456"
// Custom character sets
RandomStringUtils.random(8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
// Secure random generation
SecureRandom secureRandom = new SecureRandom();
RandomStringUtils.random(16, 0, 0, true, true, null, secureRandom);

πŸ“– Read the complete Random Utilities guide β†’

Object Utilities (ObjectUtils)

Working with objects in Java often involves handling null values, comparing objects safely, and providing default values. ObjectUtils provides comprehensive utilities for object operations.

Key Features:

Quick Example:

import org.apache.commons.lang3.ObjectUtils;
// Null-safe default values
ObjectUtils.defaultIfNull(str, "default");
ObjectUtils.firstNonNull(str1, str2, "default");
// Null-safe comparison
ObjectUtils.equals(str1, str2);
ObjectUtils.compare(str1, str2);
// Object validation
ObjectUtils.isEmpty(obj);
ObjectUtils.isNotEmpty(obj);
ObjectUtils.allNotNull(obj1, obj2, obj3);

πŸ“– Read the complete Object Utilities guide β†’

System Utilities (SystemUtils)

Working with system information, detecting operating systems, and handling platform-specific code are common requirements. SystemUtils provides comprehensive system utilities.

Key Features:

Quick Example:

import org.apache.commons.lang3.SystemUtils;
// Operating system detection
SystemUtils.IS_OS_WINDOWS; // true/false
SystemUtils.IS_OS_LINUX; // true/false
SystemUtils.IS_OS_MAC; // true/false
// Java runtime information
SystemUtils.JAVA_VERSION; // "17.0.2"
SystemUtils.JAVA_VENDOR; // "Oracle Corporation"
SystemUtils.JAVA_HOME; // "/usr/lib/jvm/java-17"
// System information
SystemUtils.OS_NAME; // "Windows 10"
SystemUtils.OS_VERSION; // "10.0"
SystemUtils.OS_ARCH; // "amd64"

πŸ“– Read the complete System Utilities guide β†’

Real-World Integration Example

Here’s how you might use multiple utilities together in a real application:

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.SystemUtils;
public class UserService {
public User createUser(String name, String email, String ageStr) {
// Validate and clean input using StringUtils
if (StringUtils.isBlank(name) || StringUtils.isBlank(email)) {
throw new IllegalArgumentException("Name and email are required");
}
String cleanName = StringUtils.trim(name);
String cleanEmail = StringUtils.trim(email);
// Parse age with NumberUtils
Integer age = NumberUtils.toInt(ageStr, 18); // Default to 18 if invalid
// Validate age range
if (!NumberUtils.isInRange(age, 0, 150)) {
throw new IllegalArgumentException("Invalid age");
}
// Create user with ObjectUtils for null safety
return new User(
ObjectUtils.defaultIfNull(cleanName, "Unknown"),
ObjectUtils.defaultIfNull(cleanEmail, "unknown@example.com"),
age
);
}
public String generateUserToken() {
// Use RandomStringUtils for secure token generation
return RandomStringUtils.randomAlphanumeric(32);
}
public String getConfigPath() {
// Use SystemUtils for cross-platform path handling
if (SystemUtils.IS_OS_WINDOWS) {
return SystemUtils.USER_HOME + "\\AppData\\Local\\MyApp";
} else if (SystemUtils.IS_OS_MAC) {
return SystemUtils.USER_HOME + "/Library/Application Support/MyApp";
} else {
return SystemUtils.USER_HOME + "/.config/myapp";
}
}
}

Best Practices

  1. Use null-safe methods when dealing with user input or external data
  2. Provide default values for optional parameters
  3. Validate input before processing
  4. Consider performance for frequently called methods
  5. Use appropriate utilities for your specific use case
  6. Handle platform differences when necessary

Performance Considerations

Common Pitfalls

  1. Not using null-safe methods - Can lead to NullPointerExceptions
  2. Hard-coding platform-specific code - Breaks cross-platform compatibility
  3. Not validating input - Can cause runtime errors
  4. Using wrong utility for the job - Choose the appropriate utility class
  5. Ignoring performance implications - Consider the impact in loops

Conclusion

Apache Commons Lang is a must-have library for any Java developer. Its utilities save time and make your code cleaner, safer, and more maintainable. The key benefits include:

Start incorporating these utilities into your projects and see how they simplify your Java development!

Detailed Guides

For comprehensive coverage of each utility category, check out these detailed guides:

Resources

Written by Purusothaman Ramanujam

← Back to blog