randomPrint() is a RandomStringUtils class that is used to generate random string consisting of printable characters.
Characters are chosen from the set of characters that matches the regex class \p{Print}. The regex \p{Print} matches all the characters that can be printed.
There are two variations to this method.
This variation of the method creates a random string whose length is the number of characters specified.
public static String randomPrint(int count)
int count: the length of random string to generate.The method returns a random string.
This variation of the method creates a random string whose length is between the inclusive minimum and the exclusive maximum.
public static String randomPrint(int minLengthInclusive, int maxLengthExclusive)
int minLengthInclusive: The inclusive minimum length of the string to generate.
int maxLengthExclusive: The exclusive maximum length of the string to generate.
The method returns a random string.
RandomStringUtilsThe definition of RandomStringUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the
commons-langpackage, refer to the Maven Repository.
You can import the RandomStringUtils class as follows.
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomStringUtils;public class Main{public static void main(String[] args){int count = 5;System.out.println("The output of RandomStringUtils.randomPrint when the length is " + count + " - " + RandomStringUtils.randomPrint(count));int minLength = 5;int maxLength = 10;System.out.println("The output of RandomStringUtils.randomPrint when the (minlength, maxlength) is (" + minLength + ", " + maxLength + ") - " + RandomStringUtils.randomPrint(minLength, maxLength));}}
count = 5In the first example, we use the first variation of the method where we specify the exact length of the generated string. The method generates the random string FZGj4 of length five consisting of printable characters.
minimum length = 5maximum length = 10In the second example, we use the second variation of the method where we specify the minimum and maximum length of the generated string. The method generates the random string v$C,eI of length six consisting of printable characters.
The output of the code is as follows:
The output of RandomStringUtils.randomPrint when the length is 5 - FZGj4
The output of RandomStringUtils.randomPrint when the (minlength, maxlength) is (5, 10) - v$C,eI
The output may differ each time the above code is run.
Free Resources