How to generate random alpha numeric String in Java

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