RandomStringUtils from Apache Commons Lang

We can use the Apache Commons Lang RandomStringUtils for generating random strings. It is used for simple cases only and the Random instance it uses is not cryptographically secure. For more advanced cases, we can the RandomStringGenerator class.

Importing Apache Commons Lang

When using Maven, you can import the Commons Lang as:

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Replace 3.12.0 with the latest version available from Maven.

For Gradle,


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

RandomStringUtils#random method

There are many overloaded random() methods. Starting with the simplest one - it takes an integer which represents the length of the random string that will be generated and returns a randomly generated string. It chooses from all character sets.

System.out.println(RandomStringUtils.random(6));

This generates a random string of six characters. When I ran this, I got mostly Unicode characters where most of them were Chinese.

Random string with letters and numbers

As we just saw, the above random() is not that useful as it picks from all character sets. There is an overloaded random() method which takes two boolean values as shown below.

public static String random(final int count, final boolean letters, final boolean numbers)

The parameters letters and numbers denote whether alphabetic and numeric characters are to be included.

Setting both to true, we have:

System.out.println(RandomStringUtils.random(6, true, true)); //JQ4Mk6

I’ve shown the example output as comment. Since we set both to true, there are alphabetic and numeric characters in the generated random string. Let us set one of them to true.

System.out.println(RandomStringUtils.random(6, false, true)); //579125
System.out.println(RandomStringUtils.random(6, true, false)); //RSZKAb

In the first call, we set letters to false and numbers parameter as true and hence the output had only numbers. Conversely, the second call had only letters set to true and hence the output had only alphabetic characters (both lower and upper case).

Specifying start and end character positions

We can pass two additional arguments viz., start and end where

  • start specifies the position in the set of characters to start at
  • End specifies the position in the set of characters to end before

The start and end refer to the ASCII values (decimal value) of character.

System.out.println(RandomStringUtils.random(6, 33, 44, false, false)); //#$&$)"

The above code prints a random string which has ASCII characters from 33 to 44 (exclusive).

Note: The end must be greater than the start parameter.

If we want to include the letter and/or numbers, then we have to pass the start and end values appropriately. Otherwise, it will throw an exception.

Example: In the below code, we ask it to include letters, but the passed range of [start, end) doesn’t include letters and hence it throws an exception.

//throws java.lang.IllegalArgumentException: Parameter end (44) must be greater then (48) for generating digits or greater then (65) for generating letters.
System.out.println(RandomStringUtils.random(6, 33, 44, true, false));

Note: Decimal value 48 is ASCII ‘0’ and 65 is ‘A’.

In the below shown code, we specify start as 48 and end as 123 which means it will include till lower-case z (‘z’). The first call includes only letters and whereas the second includes both letters and numbers.

System.out.println(RandomStringUtils.random(6, 48, 123, true, false)); //mgZLUS
System.out.println(RandomStringUtils.random(6, 48, 123, true, true)); //PbnDm6

Passing custom character set

To the above, we can pass a custom character set to choose from as a var-args of char values. In that case, the start and end values are applicable to the passed character set only.

System.out.println(RandomStringUtils.random(6, 0, 4, true, true, 'a', 'b', '0', '1', '2')); //10ab1a

Since the end is 4, it will not include character ‘2’ in the output.

And if we set letters as false, it can only pick from characters ‘0’ and ‘1’. If we set numbers to false, it will use only character ‘a’ and ‘b’.

System.out.println(RandomStringUtils.random(6, 0, 4, false, true, 'a', 'b', '0', '1', '2')); //000110
System.out.println(RandomStringUtils.random(6, 0, 4, true, false, 'a', 'b', '0', '1', '2')); //babbaa

Choosing from a specified character set

As seen in the other overloaded method, we can control the character set from which it picks the characters. We can pass the count, which specifies the number of characters in the output and a var-args of character values. When generating the random string, it only picks from the passed character values.

System.out.println(RandomStringUtils.random(6, 'a', 'b', 'c', 'd')); //cacdab

The above call will generate a random string of length six, which has only the characters [a-d]. If we pass only one character, it will be forced to use only that character.

System.out.println(RandomStringUtils.random(6, 'a')); //aaaaaa

Passing a string for the character set

Rather than passing a var-args of character, we can pass a string which denotes the character set to choose from.

System.out.println(RandomStringUtils.random(6, "abcd")); //dbcadd

Other RandomStringUtils methods

If you want to generate a random string with alphabetic/numeric/alphanumeric/ascii characters, then you don’t have to use the random() method passing boolean arguments as it is not that intuitive. There are other methods which help us to generate random strings which has alphanumeric/only alphabetic or numeric characters. Let us see them.

All these methods have two overloads

  1. Length of the random string to be generated
  2. The minimum and the maximum length of the random string where the minLength is inclusive and maxLength is exclusive. Hence the generated string’s length will be between [minLength, maxLength].
    • Note: The start value must be smaller or equal to the end value.

Random alphabetic

The randomAlphabetic generates a random string which has only alphabets. This uses the character set [a-zA-Z] for this.

To generate a random string with only alphabets of length 6,

System.out.println(RandomStringUtils.randomAlphabetic(6)); //BcpmiJ

To generate a string with only alphabets of length between say 4 and 10, we can do,

System.out.println(RandomStringUtils.randomAlphabetic(4, 11));

We are passing minLengthInclusive parameter as 4 and maxLengthExclusive as 11. The output could be like any of the below:

AVEsF
cBWr
UiRCsHxK

If the end value (max) is lesser than the start value (min), then it throws an IllegalArgumentException.

Random numeric

The randomNumeric method will return a random string which has only numbers in it. It uses [0-9] as the character set from which it will pick the characters. Let us generate a random string with only numbers of length 6.

System.out.println(RandomStringUtils.randomNumeric(6)); //035980

Now, let’s generate a random string with only numbers of length between 4 and 10.

System.out.println(RandomStringUtils.randomNumeric(4, 11));

The output could be like:

37179
88984
1676913

Random alphanumeric

The randomAlphanumeric method is like a combination of randomAlphabetic and randomNumeric methods. The generated random string will have alphabets and numbers. As seen before, we can either generate a random string of a fixed length or we can specify the min and max length of the string.

System.out.println(RandomStringUtils.randomAlphanumeric(6)); //kMWZ2u
System.out.println(RandomStringUtils.randomAlphanumeric(4, 11)); //7e0YPLW6

Random ascii

The randomAscii method generates random string using ASCII values between 32 and 126 (inclusive).

System.out.println(RandomStringUtils.randomAscii(6)); //=QWz #
System.out.println(RandomStringUtils.randomAscii(4, 11)); //S$t[J8 Y

Random print and graph

The randomPrint method uses the print character class as the character set for producing random string and the print character class includes alphabet, numbers, blank spaces.

On the other hand, the randomGraph uses the graph character class. It is like the print character class but excludes spaces.

System.out.println(RandomStringUtils.randomPrint(6)); //%Z4\jj
System.out.println(RandomStringUtils.randomPrint(4, 11)); //:' =P

System.out.println(RandomStringUtils.randomGraph(6)); ///0#2Wq
System.out.println(RandomStringUtils.randomGraph(4, 11)); //K|QGq

Conclusion

In this post, we learn about the Apache Commons Lang RandomStringUtils class. Check out the other apache-commons posts.