Disclosure: This article may contain affiliate links. When you purchase, we may earn a small commission.

3 Examples to Generate Random Alphanumeric String in Java - UUID Example

Many times we need random alphanumeric String for one or another purpose and Thankfully Java provides a couple of ways to create random Strings which can be numeric, alphanumeric, or simply alphabetic. If you are familiar with Java API to generate random numbers like java.util.Random class and Math.random() method than It's quite easy to create an array with choice of characters like Alphanumeric, numeric, alphabets, special characters, and choose random characters to construct random String. If you like using an open-source library and happen to be using Apache commons-lang then generating an alphanumeric String is just one line of code as shown in the first example in our Java program. 

Apache commons-lang provides RandomStringUtils class, which provides a convenient method to generate random alphanumeric, numeric, alphabetic, or ASCII string with the specified length. You can even use java.util.UUID class to generate random String in Java.

Though the UUID class doesn't provide control on the length and it also contains dashes, You can easily remove those shortcomings by adding few lines of code. In this Java tutorial, we will see 3 examples to generate random alphanumeric, numeric, and alphabetic String in Java with the specified length.

Btw, if you are new to the Java programming world then I highly recommend you to join a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka and his team on Udemy. This 80+ hour course is the most up-to-date and comprehensive course to learn Java and it's also very affordable. 

How to generate alphanumeric random String in Java

As I said we will look at 3 different ways to generate alphanumeric String in Java, Using :

1) Apache commons-lang RandomStringUtils
2) Java UUID class
3) Math.random() method

RandomStringUtils is one of the easiest ways to generate random String in Java. In this Java program, we will see how to generate numeric, alphabetic, and alphanumeric String in Java using this class. java.util.UUID is another great solution to generate random String in Java.

It provides a good degree of randomness but if you are strictly looking for an alphanumeric String then you might need to compromise a bit as UUID generated in Java contains a dash ("-"). Though You can still remove all dash by compromising some degree of randomness.

Another way to generate random Strings in Java both alphanumeric and numeric is to use the  Math.random() class just like we used it for generating random numbers and pick a random character from a defined character set like a set of uppercase and lowercase alphabets and numbers. We will see an example of one such method in Java here.

And, if you want to know more about the Math.random() method, you can also check this Java Programming Essentials: AP Computer Science A  course on Udemy where you will build SubstractionQuiz using a random number. 

3 Examples to Generate Random Alphanumeric String in Java - UUID Example

Alphanumeric Random String example in Java

Here is a complete code example of generating numeric, alphabetic, and alphanumeric String in Java using Apache commons-lang, Java UUID, and Math.random() method. In this example, except for UUID, we have generated a random string with a length of 10.

And, here is the complete Java program which you can copy in your IDE and run.
package test;
import java.util.UUID; 
import java.util.logging.Logger; 
import org.apache.commons.lang.RandomStringUtils;
  * Java program to generate numeric, alphabetic and alphanumeric String in Java.
   * This examples uses Commons RandomStringUtils, java.util.UUID and Math.random()
   * method.  
  * @author Javin Paul 
public class RandomStringGenerator {
    private static final Logger logger 
            = Logger.getLogger(StringReplace.class.getName());
    public static void main(String args[]) {
        //generating random alphanumeric String in Java using Apache commons 
        String random = RandomStringUtils.randomAlphanumeric(10);
        System.out.println("Random alphanumeric String in Java using commons 
                               RandomStringUtils      : " + random);
        System.out.println("Random numeric String generated in Java  : " 
                               + RandomStringUtils.randomNumeric(10));
        System.out.println("Random alphabetic String in Java using created 
             by RandmomStringUtils    : " + RandomStringUtils.randomAlphabetic(10));
        //random String in Java using UUID class      
        random = UUID.randomUUID().toString(); 
        System.out.println("Random String generated in Java using UUID : " 
                                  + random);

        //Java code to generate random alpha numeric String in Java with specified length
        random = StringReplace.randomString(10);
        System.out.println("Random alphanumeric String generated using Math.random() : " 
                                 + random);
      * Java method, which uses Math.random() to generate random alphanumeric
      * String in Java.
    public static String randomString(int length){
        char[] ALPHANUMERIC  
        StringBuilder random = new StringBuilder();
        for(int i =0; i < length; i++) {
            int index = (int) (Math.random()ALPHANUMERIC.length);
        return random.toString();
Random alphanumeric String in Java using commons RandomStringUtils: jj3OACtUlr
Random numeric String generated in Java: 1343585742
Random alphabetic String in Java using created by RandmomStringUtils: eFqzRcfCHs
Random String generated in Java using UUID : 5a159ba8-bf8e-4b10-9119-866508ec3b5b
Random alphanumeric String generated using Math.random(): Pwpuikp8Zk

That's all on How to generate random alphanumeric String in Java. We have seen 3 different ways to generate random numeric, alphabetic, and alphanumeric String in Java. You can use any of the above approaches to generate random String with a specified length in Java. Try to run this program couple of times to see Strings generated are random.

Other Core Java Tutorials and Resources You may like
  • How to remove duplicate elements from ArrayList in Java? (tutorial)
  • Top 5 courses to learn Java Collections and Streams (best courses)
  • How to create and initialize ArrayList in the same line? (example)
  • Top 5 Java Concurrency and thread courses (best courses)
  • Difference between ArrayList and HashMap in Java? (answer)
  • Top 5 Courses to learn Spring MVC for beginners (spring courses)
  • How to loop through an ArrayList in Java? (tutorial)
  • 10 Advanced Core Java Courses for Programmers (advanced courses)
  • How to synchronize an ArrayList in Java? (read)
  • When to use ArrayList over LinkedList in Java? (answer)
  • Top 5 Courses to become full-stack Java developers (online courses)
  • How to reverse an ArrayList in Java? (example)
  • How to get a sublist from ArrayList in Java? (example)
  • 10 Free Spring Courses for Java programmers (Free courses)
  • How to sort an ArrayList in descending order in Java? (read)
  • Difference between ArrayList and HashSet in Java? (answer)
  • How to convert CSV String to ArrayList in Java? (tutorial)
  • 10 Best Spring Boot Courses for Java developers (boot courses)

Thanks for reading this article so far. If you find this article useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S, - If you are new to the Java programming world, and looking for a free online course to start with then you can also check out Java Tutorial for Complete Beginners(FREE) course on Udemy. More than 1.2 million people have joined this course to learn Java for free. All you need is a free Udemy count to join this course. 

No comments :

Post a Comment