How do I generate a random alphanumeric string?

The code below show you how to use the Apache Commons-Lang RandomStringUtils class to generate some random string data.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.RandomStringUtils;

public class RandomStringUtilsDemo {
    public static void main(String[] args) {
        // Creates a 64-chars length random string of number.
        String result = RandomStringUtils.random(64, false, true);
        System.out.println("random = " + result);

        // Creates a 64-chars length of random alphabetic string.
        result = RandomStringUtils.randomAlphabetic(64);
        System.out.println("random = " + result);

        // Creates a 32-chars length of random ascii string.
        result = RandomStringUtils.randomAscii(32);
        System.out.println("random = " + result);

        // Creates a 32-chars length of string from the defined array of
        // characters including numeric and alphabetic characters.
        result = RandomStringUtils.random(32, 0, 20, true, true,
                "qw32rfHIJk9iQ8Ud7h0X".toCharArray());
        System.out.println("random = " + result);
    }
}

The example of our program result are:

random = 6251115933802303614285104650603664973302700879175809706257640062
random = EbKuzxERdBtCCHtbRuYnLwfnirtIqkcwwHxvZofkaGLNsNblCaVoLXFxfjYjXSHk
random = v9cJK?=d-Jl b-pisn9vUGxCV1&*>StY
random = XirkhUHHfwUf3kih8Hw877882d9i8Q3q

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I find text between two strings?

In this example we’ll use the StringUtils.substringBetween() method. Here we’ll extract the title and body of our HTML document. Let’s see the code.

package org.kodejava.commons.lang;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

public class NestedString {
    public static void main(String[] args) {
        String helloHtml = "<html>" +
                "<head>" +
                "   <title>Hello World from Java</title>" +
                "<body>" +
                "Hello, today is: " + new Date() +
                "</body>" +
                "</html>";

        String title = StringUtils.substringBetween(helloHtml, "<title>", "</title>");
        String content = StringUtils.substringBetween(helloHtml, "<body>", "</body>");

        System.out.println("title = " + title);
        System.out.println("content = " + content);
    }
}

By printing out the title and content, we’ll see something similar to:

title = Hello World from Java
content = Hello, today is: Thu Sep 30 06:32:32 CST 2021

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I check for an empty string?

package org.kodejava.commons.lang;

import org.apache.commons.lang3.StringUtils;

public class EmptyStringCheckDemo {
    public static void main(String[] args) {
        // Create some variable to hold some empty string, contains only
        // whitespaces and words.
        String one = "";
        String two = "\t\r\n";
        String three = "     ";
        String four = null;
        String five = "four four two";

        // We can use StringUtils class for checking if a string is empty or not
        // using StringUtils.isBlank() method. This method will return true if
        // the tested string is empty, contains whitespaces only or null.
        System.out.println("Is one empty? " + StringUtils.isBlank(one));
        System.out.println("Is two empty? " + StringUtils.isBlank(two));
        System.out.println("Is three empty? " + StringUtils.isBlank(three));
        System.out.println("Is four empty? " + StringUtils.isBlank(four));
        System.out.println("Is five empty? " + StringUtils.isBlank(five));

        // On the other side, the StringUtils.isNotBlank() methods complement
        // the previous method. It will check if a tested string is not empty.
        System.out.println("Is one not empty? " + StringUtils.isNotBlank(one));
        System.out.println("Is two not empty? " + StringUtils.isNotBlank(two));
        System.out.println("Is three not empty? " + StringUtils.isNotBlank(three));
        System.out.println("Is four not empty? " + StringUtils.isNotBlank(four));
        System.out.println("Is five not empty? " + StringUtils.isNotBlank(five));
    }
}

Here is the result:

Is one empty? true
Is two empty? true
Is three empty? true
Is four empty? true
Is five empty? false
Is one not empty? false
Is two not empty? false
Is three not empty? false
Is four not empty? false
Is five not empty? true

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I get the nearest hour, minute, second of a date?

This example demonstrates how to use the DateUtils.round() method to get the nearest hour, minute and second of a date.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;

import java.util.Calendar;
import java.util.Date;

public class DateRoundingDemo {
    public static void main(String[] args) {
        FastDateFormat formatter = DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT;

        Date now = new Date();
        System.out.println("now = " + formatter.format(now));

        // Get the nearest second
        Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
        System.out.println("nearestSecond = " + formatter.format(nearestSecond));

        // Get the nearest minute
        Date nearestMinute = DateUtils.round(now, Calendar.MINUTE);
        System.out.println("nearestMinute = " + formatter.format(nearestMinute));

        // Get the nearest hour
        Date nearestHour = DateUtils.round(now, Calendar.HOUR);
        System.out.println("nearestHour = " + formatter.format(nearestHour));
    }
}

Here are the program results:

now = 2021-09-30T06:23:24+08:00
nearestSecond = 2021-09-30T06:23:24+08:00
nearestMinute = 2021-09-30T06:23:00+08:00
nearestHour = 2021-09-30T06:00:00+08:00

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I format date and time using DateFormatUtils class?

The DateFormatUtils class help us to format date and time information. This class uses an instance of org.apache.commons.lang3.time.FastDateFormat class to format the date and time information. Compared to Java SimpleDateFormat, the FastDateFormat class is thread safe.

If you want to create a custom date format, you can use the FastDateFormat class directly.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;

public class DateFormattingDemo {
    public static void main(String[] args) {
        Date today = new Date();

        // ISO8601 formatter for date-time without a time zone.
        // The format used is yyyy-MM-dd'T'HH:mm:ss.
        String timestamp = DateFormatUtils.ISO_8601_EXTENDED_DATETIME_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);

        // ISO8601 formatter for date-time with time zone.
        // The format used is yyyy-MM-dd'T'HH:mm:ssZZ.
        timestamp = DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);

        // The format used is EEE, dd MMM yyyy HH:mm: ss Z in US locale.
        timestamp = DateFormatUtils.SMTP_DATETIME_FORMAT.format(today);
        System.out.println("timestamp = " + timestamp);
    }
}

The result of the code snippet:

timestamp = 2021-09-30T06:18:20
timestamp = 2021-09-30T06:18:20+08:00
timestamp = Thu, 30 Sep 2021 06:18:20 +0800

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central