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

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

Hello Java programmers, if you want to create a random alphanumeric string and looking for examples then you have come to the right place. Earlier, I have shown you how to generate random numbers in a range, and in this article, you'll learn how to generate random alphanumeric String in Java. Suppose, you want to generate an alphabetic or alphanumeric string of a given length in Java? How do you do it? Well, if you are like me, you probably search a library like Apache commons-lang or Google Guava for something which can do this task. It's a good thing. There is no point in re-inventing a wheel if a tried and tested solution already exists. In fact, Effective Java, the most respected book in the Java world also suggests knowing 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 a 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 a given length in Java.




How to generate Alphabetic String of given length in Java

Let's first take a look at 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 from.

If you want you can also generate them in capital or small case, in that case, you will have 26 chatters to choose from. In order to generate a random alphabetic String of a 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 the 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 the index in a 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 a 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 that 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 every time you need a random number is not the right way to use it.

In the above code, we use a StringBuilder to create a mutable string and using the charAt() function to retrieve the characters from the random index from the source String. See these free Java courses for Beginners to learn more about String and StringBuilder class.



How to create a Random Alphanumeric String in Java? Example

Now, if you want an alphanumeric String of a given length instead of an 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 like $, #, or - then you can include them too but then your string will no longer remain alpha-numeric.

The rest of the code will remain the same i.e. you can use the same radomString() method to generate an alphanumeric string, no change on that. The same goes for generating a numeric string, all you need to do is change the source to contain only numbers like
static final String SOURCE = "0123456789";

The rest of the code will remain the 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 its own Random number generator.

If you want to know more about ThreadLocalRandom and SecureRandom and their difference, I suggest you check these advanced Java Performance courses for experienced Java developers. It's a great resource for anyone who wants to learn advanced Java concepts. 






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 lengths 10, 12, and 20 by using SecureRandom and without any third-party library, as well as 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 the  SecureRandom and ThreadLocalRandom class of JDK 7, I suggest you read these Java performance books for experienced developers. 


That's all about how to generate random alphabetic, numeric, and alphanumeric String of a 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

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

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.