How do I generate a random alpha-numeric string?

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

package org.kodejava.example.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 = 2807246146525875794860509906530938229981588250176397328237925194
random = SWMZqKHTfWkJOIMMliShJKSGHIiBcQJxukwLQxazxZymuSCyLVCDTYsFehrIPwRr
random = e}&"_8Ek%F'7&_T8\G~YPEG2#N-^_|xw
random = 0IHI8dIk2Xf0fJX0HqJr78dq7w92Qd0U

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.9</version>
</dependency>

Maven Central

1 Comments

Leave a Reply

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