What it is
Apache Commons Lang provides a host of helper utilities for the java.lang API, making everyday Java development easier. It includes functionality for String manipulation, object reflection, concurrency, number handling, date/time, and more.
Commons Lang offers utilities for String operations, Object utilities, Number utilities, Reflection, Builders, Random generation, concurrency helpers, and more. It reduces boilerplate and simplifies common coding patterns.
Installation
Add dependency in pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.13.0</version>
</dependency>Getting started
The smallest useful thing you can do with it, and what each part means.
import org.apache.commons.lang3.StringUtils;
String str = " Hello World ";
System.out.println(StringUtils.strip(str)); // Trims whitespace
System.out.println(StringUtils.isEmpty(str));import org.apache.commons.lang3.ObjectUtils;
Integer result = ObjectUtils.defaultIfNull(null, 42);
System.out.println(result);Advanced usage
Where the library earns its place over a simpler alternative.
import org.apache.commons.lang3.RandomStringUtils;
String randomStr = RandomStringUtils.randomAlphanumeric(10);
System.out.println(randomStr);import org.apache.commons.lang3.reflect.FieldUtils;
class User { private String name; }
User user = new User();
FieldUtils.writeField(user, "name", "Alice", true);
System.out.println(FieldUtils.readField(user, "name", true));import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
class User { private int id; private String name; }import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;
Date now = new Date();
Date truncated = DateUtils.truncate(now, java.util.Calendar.DAY_OF_MONTH);
System.out.println(truncated);Errors and fixes
The failures you are most likely to hit, and what actually resolves them.
- NullPointerException
- Use null-safe methods like StringUtils.isEmpty(), ObjectUtils.defaultIfNull(), etc.
- IllegalArgumentException
- Occurs when input parameters are invalid. Validate inputs before using utility methods.
Best practices
- Use StringUtils for null-safe string operations instead of manually checking nulls.
- Leverage ObjectUtils and ArrayUtils for handling nulls and defaults.
- Use builder classes for equals(), hashCode(), and toString() implementations.
- Utilize DateUtils and DurationFormatUtils for date/time operations.
- Avoid reinventing common utilities that Commons Lang already provides.
Background
Why it exists, and what it was reacting to.
Commons Lang was created to fill the gaps in the standard Java library by providing reusable, well-tested, and reliable utilities. It simplifies common tasks such as string manipulation, reflection, object comparison, and exception handling, improving productivity and code readability. It is widely used in enterprise Java applications and open-source projects.
