How to generate random alpha numeric String in Java
December 1, 2017
Following code is an example of generating a random alpha-numeric string using Java Random class. It is designed to generate random String of varying length based on the input parameter.
Here is the code
package com.zparacha.utils;
import java.util.Random;
import java.util.Scanner;
public class StringUtilities {
/**
*
* @param n
* Desired Length of random string
* @return
*/
public static String getRandomAlphNumeircString(int n) {
// Get a n-digit multiplier of 10
int maxDigit = (int) Math.pow(10, n - 2);
Random random = new Random();
/*
* Get a random character by getting a number from 0 t0 26 and then adding an
* 'A' to make it a character
*
*/
char randomCharacter = (char) (random.nextInt(26) + 'A');
/*
* Add 1*maxDigit to ensure that the number is equals to or greater than minimum
* value nextInt() method will return the number between 0 and 9*maxDigit
*/
int randomNumber = 1 * maxDigit + random.nextInt(9 * maxDigit);
return String.valueOf(randomCharacter) + randomNumber;
}
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.print("Enter desired lenght of random string: ");
int n = in.nextInt();
in.nextLine();
System.out.println("Random string = " + getRandomAlphNumeircString(n));
}
}
Method getRandomAlphNumeircString accepts a numeric parameter for the desired length of the String. Using the max length value it creates a variable maxDigit to a 10 muliple number.
It then calls Random.nextInt() method to get a number between 0 and 26 (number of English alphabets) and then adds an ‘A’ to convert that number into a character.
Next, it generates a Random number by calling Random.nextInt() method again.
Finally, it concatenates random character and the random number to generate a random alpha-numeric String.
main method is included to test getRandomAlphNumeircString method.
A sample run produced following output.
Enter desired lenght of random string: 10
Random string = W742681415
A note on java.util.Random in modern Java
Two things worth knowing if you’re writing this today rather than in 2017:
- If the random string is used for anything security-sensitive — a token, a password reset code, a session ID — don’t use
Random. It’s not cryptographically secure, and its output is predictable if an attacker knows (or can guess) the seed. UseSecureRandominstead; it’s a drop-in replacement with the samenextInt()API. - Since Java 17,
Randomalso implements the newerRandomGeneratorinterface, and the JDK now ships several modern generator algorithms viaRandomGeneratorFactory(e.g.RandomGeneratorFactory.of("L64X128MixRandom").create()) that produce better statistical quality than the legacyRandomfor non-security use cases like simulations or test data.Randomitself isn’t deprecated and still works fine on JDK 21 — this is only worth reaching for if you specifically need the improved randomness quality.