0
# Apache Commons Lang 3.18.0
1
2
Apache Commons Lang is a comprehensive utility library that provides a rich set of helpers for Java development. This library contains 223+ public classes across 16 packages with over 2000 public static utility methods, making it one of the most essential libraries for Java developers.
3
4
## Package Information
5
6
```xml { .api }
7
<dependency>
8
<groupId>org.apache.commons</groupId>
9
<artifactId>commons-lang3</artifactId>
10
<version>3.18.0</version>
11
</dependency>
12
```
13
14
**Maven Coordinates:** `org.apache.commons/commons-lang3@3.18.0`
15
**Java Version:** Java 8+
16
**License:** Apache License 2.0
17
18
## Core Imports
19
20
The most commonly used classes can be imported as follows:
21
22
```java { .api }
23
// String utilities
24
import org.apache.commons.lang3.StringUtils;
25
import org.apache.commons.lang3.CharUtils;
26
27
// Array utilities
28
import org.apache.commons.lang3.ArrayUtils;
29
30
// Object utilities
31
import org.apache.commons.lang3.ObjectUtils;
32
import org.apache.commons.lang3.ClassUtils;
33
import org.apache.commons.lang3.BooleanUtils;
34
35
// Math utilities
36
import org.apache.commons.lang3.math.NumberUtils;
37
38
// Builder pattern utilities
39
import org.apache.commons.lang3.builder.ToStringBuilder;
40
import org.apache.commons.lang3.builder.EqualsBuilder;
41
import org.apache.commons.lang3.builder.HashCodeBuilder;
42
43
// Validation
44
import org.apache.commons.lang3.Validate;
45
46
// Date/Time utilities
47
import org.apache.commons.lang3.time.DateUtils;
48
import org.apache.commons.lang3.time.StopWatch;
49
50
// Exception handling
51
import org.apache.commons.lang3.exception.ExceptionUtils;
52
```
53
54
## Key APIs Overview
55
56
### String Manipulation
57
StringUtils provides 233+ null-safe string operations:
58
59
```java { .api }
60
// Null-safe string operations
61
String result = StringUtils.defaultString(null, "default"); // "default"
62
boolean empty = StringUtils.isEmpty(null); // true
63
boolean blank = StringUtils.isBlank(" "); // true
64
String clean = StringUtils.trimToNull(" text "); // "text"
65
66
// String formatting and manipulation
67
String abbrev = StringUtils.abbreviate("Long text here", 10); // "Long te..."
68
String padded = StringUtils.leftPad("123", 5, '0'); // "00123"
69
String joined = StringUtils.join(Arrays.asList("a", "b"), ","); // "a,b"
70
```
71
72
### Array Operations
73
ArrayUtils provides 368+ methods for array manipulation:
74
75
```java { .api }
76
// Array creation and manipulation
77
int[] array = ArrayUtils.add(new int[]{1, 2}, 3); // [1, 2, 3]
78
boolean contains = ArrayUtils.contains(array, 2); // true
79
int[] reversed = ArrayUtils.reverse(array); // [3, 2, 1]
80
String[] subarray = ArrayUtils.subarray(new String[]{"a", "b", "c"}, 1, 3);
81
82
// Null-safe operations
83
boolean isEmpty = ArrayUtils.isEmpty(null); // true
84
int length = ArrayUtils.getLength(array); // 3
85
```
86
87
### Object Utilities
88
ObjectUtils provides null-safe object operations:
89
90
```java { .api }
91
// Null-safe operations
92
String result = ObjectUtils.defaultIfNull(null, "default"); // "default"
93
String first = ObjectUtils.firstNonNull(null, null, "value"); // "value"
94
boolean allNull = ObjectUtils.allNull(null, null); // true
95
96
// Object comparison and cloning
97
int comparison = ObjectUtils.compare("a", "b"); // -1
98
Object cloned = ObjectUtils.clone(originalObject);
99
```
100
101
### Validation
102
The Validate class provides argument validation with clear error messages:
103
104
```java { .api }
105
// Argument validation
106
Validate.notNull(object, "Object cannot be null");
107
Validate.notEmpty(collection, "Collection cannot be empty");
108
Validate.inclusiveBetween(1, 10, value, "Value must be between 1 and 10");
109
Validate.isTrue(condition, "Condition must be true");
110
```
111
112
## Architecture
113
114
Apache Commons Lang is organized into focused packages:
115
116
- **org.apache.commons.lang3** - Core utility classes
117
- **org.apache.commons.lang3.builder** - Builder pattern utilities
118
- **org.apache.commons.lang3.math** - Mathematical operations
119
- **org.apache.commons.lang3.time** - Date and time utilities
120
- **org.apache.commons.lang3.concurrent** - Concurrency utilities
121
- **org.apache.commons.lang3.exception** - Exception handling
122
- **org.apache.commons.lang3.reflect** - Reflection utilities
123
- **org.apache.commons.lang3.tuple** - Tuple classes (Pair, Triple)
124
125
## Basic Usage
126
127
Here's a quick example showing common patterns:
128
129
```java { .api }
130
import org.apache.commons.lang3.*;
131
import org.apache.commons.lang3.builder.*;
132
import org.apache.commons.lang3.math.*;
133
134
public class CommonsLangExample {
135
public void demonstrateUsage() {
136
// String operations
137
String input = null;
138
String safe = StringUtils.defaultString(input, "N/A");
139
140
// Array operations
141
String[] array = {"apple", "banana", "cherry"};
142
boolean hasApple = ArrayUtils.contains(array, "apple");
143
144
// Number parsing
145
int number = NumberUtils.toInt("123", 0);
146
147
// Validation
148
Validate.notEmpty(array, "Array cannot be empty");
149
150
// Builder pattern
151
String description = new ToStringBuilder(this)
152
.append("safe", safe)
153
.append("hasApple", hasApple)
154
.append("number", number)
155
.toString();
156
}
157
}
158
```
159
160
## Functional Areas
161
162
This library is organized into several functional areas, each with comprehensive documentation:
163
164
### [String Utilities](string-utilities.md)
165
- **StringUtils** (233 methods) - Comprehensive string manipulation
166
- **CharUtils** (25 methods) - Character operations and validation
167
- **CharSetUtils** - Character set operations
168
- **RegExUtils** - Regular expression utilities
169
170
### [Array Utilities](array-utilities.md)
171
- **ArrayUtils** (368 methods) - Complete array manipulation toolkit
172
- **ArraySorter** - Array sorting utilities
173
- **ArrayFill** - Array filling operations
174
175
### [Object Utilities](object-utilities.md)
176
- **ObjectUtils** (52 methods) - Null-safe object operations
177
- **ClassUtils** (54 methods) - Class introspection and utilities
178
- **BooleanUtils** (46 methods) - Boolean operations and conversions
179
180
### [Math Utilities](math-utilities.md)
181
- **NumberUtils** (82 methods) - Number parsing and validation
182
- **Range** classes - Range operations and validation
183
- **Fraction** - Fraction arithmetic operations
184
185
### [Date/Time Utilities](date-time-utilities.md)
186
- **DateUtils** (52 methods) - Date manipulation and formatting
187
- **StopWatch** - Performance timing
188
- **DurationFormatUtils** - Duration formatting
189
190
### [Builder Utilities](builders.md)
191
- **ToStringBuilder** - Fluent toString() method construction
192
- **EqualsBuilder** - Fluent equals() method construction
193
- **HashCodeBuilder** - Fluent hashCode() method construction
194
- **CompareToBuilder** - Fluent compareTo() method construction
195
196
### [Validation Utilities](validation-utilities.md)
197
- **Validate** (51 methods) - Comprehensive argument validation
198
- Input validation with clear error messages
199
- Range and boundary checking
200
201
### [Concurrent Utilities](concurrent-utilities.md)
202
- Thread-safe initializers and factories
203
- Circuit breakers for fault tolerance
204
- Background task execution utilities
205
206
### [Exception Utilities](exception-utilities.md)
207
- **ExceptionUtils** (35 methods) - Exception analysis and handling
208
- Stack trace utilities and cause extraction
209
- Contextual exception handling
210
211
## Performance and Best Practices
212
213
Apache Commons Lang is designed for high performance with minimal overhead:
214
215
- **Null Safety**: All utility methods handle null inputs gracefully
216
- **Immutability**: Most operations return new objects rather than modifying inputs
217
- **Thread Safety**: Utility classes are thread-safe for concurrent use
218
- **Zero Dependencies**: No external dependencies beyond Java standard library
219
220
### Memory Usage
221
- Utility classes use static methods to minimize object creation
222
- Builder classes reuse internal buffers where possible
223
- Array operations minimize copying when feasible
224
225
### Common Patterns
226
```java { .api }
227
// Defensive programming with null checks
228
String result = StringUtils.trimToNull(input);
229
if (StringUtils.isNotBlank(result)) {
230
// Process non-blank string
231
}
232
233
// Fluent validation
234
Validate.notNull(user, "User cannot be null")
235
.notEmpty(user.getName(), "Name cannot be empty");
236
237
// Builder pattern for complex objects
238
String description = ToStringBuilder.reflectionToString(object,
239
ToStringStyle.SHORT_PREFIX_STYLE);
240
```
241
242
## Integration Examples
243
244
### Spring Framework Integration
245
```java { .api }
246
@Component
247
public class UserService {
248
249
public User createUser(String name, String email) {
250
Validate.notBlank(name, "Name is required");
251
Validate.notBlank(email, "Email is required");
252
253
String cleanName = StringUtils.trim(name);
254
String normalizedEmail = StringUtils.lowerCase(email);
255
256
return new User(cleanName, normalizedEmail);
257
}
258
}
259
```
260
261
### Testing Support
262
```java { .api }
263
@Test
264
public void testUserValidation() {
265
// Using ArrayUtils for test data
266
String[] validNames = {"John", "Jane", "Bob"};
267
String[] invalidNames = {null, "", " "};
268
269
for (String name : validNames) {
270
assertDoesNotThrow(() -> userService.createUser(name, "test@example.com"));
271
}
272
273
for (String name : invalidNames) {
274
assertThrows(IllegalArgumentException.class,
275
() -> userService.createUser(name, "test@example.com"));
276
}
277
}
278
```
279
280
## Migration and Compatibility
281
282
### From Commons Lang 2.x
283
Most methods are backward compatible, with key improvements:
284
- Package name changed from `org.apache.commons.lang` to `org.apache.commons.lang3`
285
- Enhanced null safety across all utility methods
286
- New builder classes and functional programming support
287
- Improved performance and reduced memory footprint
288
289
### Java Version Compatibility
290
- **Java 8+**: Full feature support including lambda integration
291
- **Java 11+**: Enhanced with newer Java features
292
- **Java 17+**: Optimized for modern JVM performance
293
294
## Common Use Cases
295
296
1. **Input Validation**: Use Validate class for comprehensive argument checking
297
2. **String Processing**: StringUtils for all text manipulation needs
298
3. **Array Operations**: ArrayUtils for collection-like operations on arrays
299
4. **Object Construction**: Builder classes for clean object creation
300
5. **Error Handling**: ExceptionUtils for robust exception management
301
6. **Performance Monitoring**: StopWatch for timing operations
302
7. **Type Safety**: NumberUtils for safe number parsing and conversion
303
304
This library serves as the foundation for robust, maintainable Java applications by providing well-tested, performant utilities for common programming tasks.