When you develop some applications in Java or on Android platform, you can sometimes need to generate a random alpha-numeric String to generate a session id, a unique temporary id or simply to generate sample string data. Use cases are multiples and to make that there are a lot of possibilities.

In the following of this tutorial, we’re going to see several solutions that you can use. Don’t hesitate to leave me your solutions in comments.

Solution 1

In first solution, you can use a custom algorithm and use Random class from Java standard API like this :


public class GenerateRandomString {

 public static final String DATA = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
 public static Random RANDOM = new Random();

 public static String randomString(int len) {
   StringBuilder sb = new StringBuilder(len);

   for (int i = 0; i < len; i++) {
     sb.append(DATA.charAt(RANDOM.nextInt(DATA.length())));
   }

   return sb.toString();
 }

}

With that solution, you can choose the characters used in String generated by changing DATA content. However, this solution uses Random class so if it’s used to generate passwords from a server, it might be vulnerable to attacks.

To call the static method you can write this :

GenerateRandomString.randomString(30)


Solution 2

With the second solution, you can choose to use a third-party library like Apache Commons for Java and its RandomStringUtils class which you can access Javadoc here : https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/RandomStringUtils.html

Solution with RandomStringUtils is very simple :

RandomStringUtils.randomAlphanumeric(30).toUpperCase();


Solution 3

A few people think about it, but use UUID class from Java standard SDK is a very convenient method to achieve the problem. Solution is simple :

UUID.randomUUID().toString();

In addition of the concision of the solution, a major benefit of UUID solution it is almost impossible to have 2 strings generated that collide. Wikipedia tells us what is the the risk to have duplicates in probability :

“only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%”


Solution 4

Last solution presented here is also the most expensive in generation time because it uses SecureRandom Java class. But thanks to SecureRandom Java class that chooses a number of bits from a cryptographical secure random bit generator, this solution is secure to generate passwors on a server for example.

Code is like this :


public class MostSecureRandom {
  private static SecureRandom SECURE_RANDOM = new SecureRandom();

  public static String nextSessionId() {
    return new BigInteger(130, SECURE_RANDOM).toString(32);
  }
}

Most secure random and also most expensive because there is a big initialisation time.

Multiple solutions exist, so you must choose solution that is the most adapted to your needs.