How to Create Random Alphabetic or AlphaNumeric String of given length in Java - Example

Suppose, you want to generate an alphabetic or alpha-numeric string of given length in Java? How do you do it? Well, if you are like me, you probably search a library e.g. Apache commons-lang for something which can do this task. It's a good thing. There is no point on re-inventing a wheel if a tried and tested solution already exists. In fact, Effective Java, the most respected book in Java world also suggest to know and use your library. In fact, Apache commons-lang does have a class called RandomStringUtils, which allows you to generate Random alphanumeric String in just one method call as shown below:

RandomStringUtils.randomAlphanumeric(20).toUpperCase();

This works great for many practical purposes but if you are generating security sensitive identifier then this is not 100% secure.

The RandomStringUtils class uses an instance of java.util.Random instantiated without arguments and as per Javadoc, the java.util.Random will use current system time if no seed is provided. This means that it can not be used for session identifiers or security sensitive keys since an attacker can easily predict what the generated session identifiers are at any given time.

The JDK 7 introduced a newer SecureRandom class which provides better security as compared to java.util.Random and provides a cryptographically strong random number generator. I'll show you can use that to generate an alphabetic, numeric or alphanumeric string of given length in Java.




How to generate Alphabetic String of given length in Java

Let's first take a look how you can generate an alphabetic string, which just comprises alphabets. They may contain small and capital letters which means you total 26 + 26 = 52 letters to choose.

If you want you can also generate them in capital or small case, in that case, you will have 26 chatters to choose. In order to generate random alphabetic String of given length, we first create a source String by concatenating all possible characters as shown below:

static final String SOURCE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

And then we'll use SecureRandom number to generate a random integer in a range i.e. from 0 to 51 because our source string has only 52 characters and index in string starts from 0 and goes till length -1. We can then use that random int to pick the character from the source string.

Just repeat this process until you have a random string of given length. For example, if you need to generate a random alphabetic string of length 10 then repeat the steps in a loop 10 times.

Even better, if  you can write a method which accepts length as a parameter and encapsulates the logic to generate alphabetic random string as shown below:

  public static String randomString(int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++)
      sb.append(SOURCE.charAt(secureRnd.nextInt(SOURCE.length())));
    return sb.toString();
  }

Here secureRnd is an instance of SecureRandom class, which is maintained in a class variable so that everyone can reuse it. If you have read my post about generating random int values in the range, you might remember that creating a new instance of java.util.Random or SecureRandom everytime you need a random number is not the right way to use it.

In above code, we use a StringBuilder to create a mutable string and using charAt() function to retrieve the characters from random index from source String. See The Complete Java Master Class to learn more about String and StringBuilder class.



How to create random alphanumeric string in Java

Now, if you want an alphanumeric String of given length instead of alphabetic string then you just need to change the SOURCE string to include numbers or digits e.g from 0 to 0 as shown below:

static final String SOURCE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

If you want to include some special characters e.g. $, #, or - then you can include them too but then your string will no longer remain alpha-numeric.

The rest of the code will remain same i.e. you can use the same radomString() method to generate an alphanumeric string, no change on that. Same goes for generating a numeric string, all you need to do is change the source to contain only numbers e.g.

static final String SOURCE = "0123456789";

The rest of the code will remain same. You can also choose to include special characters if you want.

Btw, if security is not your concern you can also use the ThreadLocalRandom class of JDK 7, it provides better performance in the concurrent environment because each thread keeps their own Random number generator.

If you want to know more about ThreadLocalRandom and SecureRandom and their difference, I suggest you check the Java Performance The Definitive Guide By Scott Oaks.

SecureRandom and threadLocalRandom in Java


Java Program to Generate Random AlphaBatic and AlphaNumeric String

Now, that you know how you can use SecureRandom or ThreadLocalRandom class to generate a random string of given length and characters e.g. alphabetic, alphanumeric, and numeric. Let's see them in action by writing a complete Java program.

import java.security.SecureRandom;
import java.util.Random;

import org.apache.commons.lang3.RandomStringUtils;

public class Helloworld {

  private static final Random generator = new Random();
  static final String SOURCE = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      + "abcdefghijklmnopqrstuvwxyz";
  static SecureRandom secureRnd = new SecureRandom();

  public static void main(String[] args) {
    System.out.println("5 random alphanumeric string with length 10");
    for (int i = 0; i < 5; i++) {
      String alpha = randomString(10);
      System.out.println(alpha);
    }

    System.out.println("5 random alphanumeric string with length 12");
    for (int i = 0; i < 5; i++) {
      String beta = randomString(10);
      System.out.println(beta);
    }

    System.out.println("5 random alphanumeric string with length 20"
        + " generated using Apache Commons lang");
    for (int i = 0; i < 5; i++) {
      String random = RandomStringUtils.randomAlphanumeric(20).toUpperCase();
      System.out.println(random);
    }
  }

  public static String randomString(int length) {
    StringBuilder sb = new StringBuilder(length);
    for (int i = 0; i < length; i++)
      sb.append(SOURCE.charAt(secureRnd.nextInt(SOURCE.length())));
    return sb.toString();
  }

}

Output
5 random alphanumeric string with length 10
e8ns3SU0fm
emKTmPoSE6
GWtuQaIwEe
ml4Ke4YEEW
wCfHObQwNL
5 random alphanumeric string with length 12
kcertwf9iD
nNnX4kouPO
TFL7elKukQ
hfJoh6nKjI
d2VsZ52CIw
5 random alphanumeric string with length 20 generated using Apache Commons Lang
NJ8RRJ3C1JB6YWRGS8RN
YR9ITCGHNFP78TH7MZRS
L4UARS7IXOCCCYUMYSDR
GRUQF74FR4PFKFHVXA3U
I7UVDHDCYUOIWA2NA6RQ

In this program, I have shown you how you can generate a random Alphanumeric string with length 10, 12 and 20 by using SecureRandom and without any third-party library, as well by using the Apache Commons Lang library.

Though I suggest you use the SecureRandom because if a functionality is available in JDK better leverage it. It is also more secure and up-to-date.  If you want to learn more about SecureRandom and ThreadLocalRandom class of JDK 7, I suggest you read Java Performance The Definitive Guide By Scott Oaks.


That's all about how to generate random alphabetic, numeric, and alphanumeric String of given length in Java. Ideally, you should use SecureRandom class but that's only available from JDK 7, if you don't mind a pseudo-random or running on JDK 6 or lower version then you can also use the java.util.Random class.

Other Java and String resources you may like
The Complete Java Master Class
Beginning Java 8 Language Features by Kishori Sharan
5 ways to compare String in Java?

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

No comments:

Post a Comment