Guide to Apache Commons Lang3 in Java

Introduction to Apache Commons Lang3

Apache Commons Lang3 is a library that provides a host of helper utilities for the java.lang API, enhancing core Java capabilities. This guide will cover installation, basic usage, advanced features, and various use cases of Apache Commons Lang3 using the latest version.

Installation

Adding Apache Commons Lang3 to Your Project

To use Apache Commons Lang3, add the following dependency to your pom.xml if you're using Maven:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version> <!-- or the latest version -->
</dependency>

For Gradle:

implementation 'org.apache.commons:commons-lang3:3.12.0'

String Utilities

Checking for Empty Strings

Apache Commons Lang3 provides utilities for checking whether a string is empty.

import org.apache.commons.lang3.StringUtils;

public class StringUtilsExample {
    public static void main(String[] args) {
        String emptyString = "";
        String nullString = null;
        String nonEmptyString = "Amit";

        System.out.println(StringUtils.isEmpty(emptyString)); // true
        System.out.println(StringUtils.isEmpty(nullString)); // true
        System.out.println(StringUtils.isEmpty(nonEmptyString)); // false
    }
}

Explanation: This example uses StringUtils.isEmpty to check if strings are empty or null.

Output:

true
true
false

Joining Strings

Joining multiple strings can be done easily with StringUtils.

import org.apache.commons.lang3.StringUtils;

public class StringJoinExample {
    public static void main(String[] args) {
        String[] names = {"Amit", "Priya", "Vikas"};
        String joinedNames = StringUtils.join(names, ", ");
        System.out.println(joinedNames);
    }
}

Explanation: This example uses StringUtils.join to join an array of strings with a delimiter.

Output:

Amit, Priya, Vikas

Capitalizing Strings

Capitalizing the first letter of a string is straightforward with StringUtils.

import org.apache.commons.lang3.StringUtils;

public class CapitalizeExample {
    public static void main(String[] args) {
        String name = "amit";
        String capitalized = StringUtils.capitalize(name);
        System.out.println(capitalized);
    }
}

Explanation: This example uses StringUtils.capitalize to capitalize the first letter of a string.

Output:

Amit

Reversing Strings

Reversing a string is simple with StringUtils.

import org.apache.commons.lang3.StringUtils;

public class ReverseStringExample {
    public static void main(String[] args) {
        String name = "Amit";
        String reversed = StringUtils.reverse(name);
        System.out.println(reversed);
    }
}

Explanation: This example uses StringUtils.reverse to reverse a string.

Output:

timA

Number Utilities

Checking for Numeric Strings

You can check if a string is numeric using NumberUtils.

import org.apache.commons.lang3.math.NumberUtils;

public class NumericCheckExample {
    public static void main(String[] args) {
        String numericString = "12345";
        String nonNumericString = "123A";

        System.out.println(NumberUtils.isCreatable(numericString)); // true
        System.out.println(NumberUtils.isCreatable(nonNumericString)); // false
    }
}

Explanation: This example uses NumberUtils.isCreatable to check if strings are numeric.

Output:

true
false

Finding the Maximum Value

Finding the maximum value in an array is easy with NumberUtils.

import org.apache.commons.lang3.math.NumberUtils;

public class MaxValueExample {
    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25};
        int max = NumberUtils.max(numbers);
        System.out.println(max);
    }
}

Explanation: This example uses NumberUtils.max to find the maximum value in an array.

Output:

25

Finding the Minimum Value

Finding the minimum value in an array is simple with NumberUtils.

import org.apache.commons.lang3.math.NumberUtils;

public class MinValueExample {
    public static void main(String[] args) {
        int[] numbers = {5, 10, 15, 20, 25};
        int min = NumberUtils.min(numbers);
        System.out.println(min);
    }
}

Explanation: This example uses NumberUtils.min to find the minimum value in an array.

Output:

5

Date Utilities

Formatting Dates

Formatting dates can be done using DateFormatUtils.

import org.apache.commons.lang3.time.DateFormatUtils;
import java.util.Date;

public class DateFormatExample {
    public static void main(String[] args) {
        Date date = new Date();
        String formattedDate = DateFormatUtils.ISO_8601_EXTENDED_DATE_FORMAT.format(date);
        System.out.println(formattedDate);
    }
}

Explanation: This example uses DateFormatUtils to format the current date in ISO 8601 format.

Output:

2024-05-17

Adding Time to Dates

You can add time to dates using DateUtils.

import org.apache.commons.lang3.time.DateUtils;
import java.util.Date;

public class AddTimeExample {
    public static void main(String[] args) {
        Date now = new Date();
        Date oneHourLater = DateUtils.addHours(now, 1);
        System.out.println(now);
        System.out.println(oneHourLater);
    }
}

Explanation: This example uses DateUtils.addHours to add one hour to the current date.

Output:

Fri May 17 12:00:00 IST 2024
Fri May 17 13:00:00 IST 2024

Random Utilities

Generating Random Strings

Generating random strings can be done using RandomStringUtils.

import org.apache.commons.lang3.RandomStringUtils;

public class RandomStringExample {
    public static void main(String[] args) {
        String randomString = RandomStringUtils.randomAlphanumeric(10);
        System.out.println(randomString);
    }
}

Explanation: This example uses RandomStringUtils.randomAlphanumeric to generate a random alphanumeric string of length 10.

Output:

aB3dEfG7Hj

Generating Random Numbers

Generating random numbers can be done using RandomUtils.

import org.apache.commons.lang3.RandomUtils;

public class RandomNumberExample {
    public static void main(String[] args) {
        int randomNumber = RandomUtils.nextInt(1, 100);
        System.out.println(randomNumber);
    }
}

Explanation: This example uses RandomUtils.nextInt to generate a random number between 1 and 100.

Output:

42

Object Utilities

Checking for Null Objects

You can check if an object is null using ObjectUtils.

import org.apache.commons.lang3.ObjectUtils;

public class NullCheckExample {
    public static void main(String[] args) {
        String name = null;
        String defaultName = "Default";

        String result = ObjectUtils.defaultIfNull(name, defaultName);
        System.out.println(result);
    }
}

Explanation: This example uses ObjectUtils.defaultIfNull to return a default value if the object is null.

Output:

Default

Comparing Objects

Comparing objects can be done using ObjectUtils.

import org.apache.commons.lang3.ObjectUtils;

public class CompareExample {
    public static void main(String[] args) {
        String name1 = "Amit";
        String name2 = "Vikas";

        int comparison = ObjectUtils.compare(name1, name2);
        System.out.println(comparison);
    }
}

Explanation: This example uses ObjectUtils.compare to compare two strings.

Output:

-1

Array Utilities

Checking if an Array is Empty

You can check if an array is empty using ArrayUtils.

import org.apache.commons.lang3.ArrayUtils;

public class ArrayEmptyCheckExample {
    public static void main(String[] args) {
        String[] names = {};
        boolean isEmpty = ArrayUtils.isEmpty(names);
        System.out.println(isEmpty);
    }
}

Explanation: This example uses ArrayUtils.isEmpty to check if an array is empty.

Output:

true

Adding Elements to an Array

You can add elements to an array using ArrayUtils.

import org.apache.commons.lang3.ArrayUtils;

public class AddElementExample {
    public static void main(String[] args) {
        String[] names = {"Amit", "Priya"};
        names = ArrayUtils.add(names, "Vikas");
        for (String name : names) {
            System.out.println(name);
        }
    }
}

Explanation: This example uses ArrayUtils.add to add an element to an array.

Output:

Amit
Priya
Vikas

Removing Elements from an Array

You can remove elements from an array using ArrayUtils.


import org.apache.commons.lang3.ArrayUtils;

public class RemoveElementExample {
    public static void main(String[] args) {
        String[] names = {"Amit", "Priya", "Vikas"};
        names = ArrayUtils.removeElement(names, "Priya");
        for (String name : names) {
            System.out.println(name);
        }
    }
}

Explanation: This example uses ArrayUtils.removeElement to remove an element from an array.

Output:

Amit
Vikas

Conclusion

Apache Commons Lang3 is a versatile and powerful library that enhances the core Java capabilities with a variety of utility classes. This guide covered the basics of string, number, date, random, object, and array utilities, providing examples and explanations for each use case. 

By leveraging Apache Commons Lang3, you can simplify and enhance your Java code. For more detailed information and advanced features, refer to the official Apache Commons Lang documentation.

Comments