Example to Generate Random Alpha Numeric Text

This example shows how to generate random alpha numeric text which is not easy to guess.

Tools and Technologies used in this article

  1. JDK 1.6
  2. Eclipse 3.7

1. Code

File: AlphaNumericTextGenerator.java

package com.srccodes.examples.java;
 
import java.math.BigInteger;
import java.security.SecureRandom;
 
/**
 * @author Abhijit Ghosh
 * @version 1.0
 */
public class AlphaNumericTextGenerator {
    private static final int MAXIMUM_BIT_LENGTH = 100;
    private static final int RADIX = 32;
 
    public static void main(String[] args) {
        String randomText = getRandomText();
         
        System.out.println("Generated random alpha numeric text : " + randomText);
    }
 
    public static String getRandomText() {
        // cryptographically strong random number generator
        SecureRandom random = new SecureRandom();
 
        // randomly generated BigInteger
        BigInteger bigInteger = new BigInteger(MAXIMUM_BIT_LENGTH, random);
 
        // String representation of this BigInteger in the given radix.
        String randomText = bigInteger.toString(RADIX);
         
        return randomText;
    }
}

2. Console Output

Above code will randomly generate a new alpha numeric text for each time.

Console

Generated random alpha numeric text : qa3m5ls6brtoq737vhlj

Download SrcCodes

All code samples shown in this post are available in the following link RandomAlphaNumericTextGenerator.zip

References