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

Wayan

1 Comments

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.