Share on Google+Share on Google+

Random alpha numeric string of fixed size

In this section, you will learn to generate fixed size alpha numeric string using core Java code.

Random alpha numeric string of fixed size

In this section, you will learn to generate fixed size alpha numeric string using core Java code.

In some situations, we need alphanumeric string of fixed size. For example, for generating default auto generated password or some key to identify user or task. Also this kind of alphanumeric key is also utilized to URL shortening.

Given below two examples of generating random alphanumeric keys :


In the below example, we are going to generate 5 character long alphanumeric string randomly using  java.util.Math :

package alphaNumricRandomString;

public class GenerateRandomString {
private static final String ALPHA_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static void main(String[] args) {
GenerateRandomString grs = new GenerateRandomString();
System.out.println("Generated random String is :"+grs.getAlphaNumeric(5));

public String getAlphaNumeric(int len) {
StringBuffer sb = new StringBuffer(len);
for (int i = 0; i < len; i++) {
int ndx = (int) (Math.random() * ALPHA_NUM.length());
return sb.toString();

Math.random( ) returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

In the above code, the value generated by Math.random() is multiplied by length of  ALPHA_NUM string and the result is converted into integer and stored into ndx variable which decide which character to pick from the ALPHA_NUM string.

StringBuffer  is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. String objects are constants and immutable. But in StringBuffer  ,the length and the sequence can be changed through certain method calls.


C:\ Random 5 character AlphaNumeric String >java GenerateRandomString
Generated random String is :V4UQN                                                                                                     


In this example, we are going to generate 5 character long alphanumeric string randomly using ASCII code & java.util.Random :

package alphaNumricRandomString;

import java.util.Date;
import java.util.Random;

public class GenerateRandomID {
public String generateRandomID(){

final int ID_SIZE = 5;
final int NUM_OF_CHARS = 36;
StringBuffer id = new StringBuffer();
long now = new Date().getTime();

// Set the new Seed as current timestamp
Random r = new Random(now);

int index = 0;
int x = 0;

while(x < ID_SIZE){
index = r.nextInt(NUM_OF_CHARS);
System.out.println("Index="+ index);
if(index < 10){
id.append((char)(48 + index));
else if(10 <= index && index <36){
index = index - 10;
id.append((char)(97 + index));

return id.toString();
public static void main(String args[]){
GenerateRandomID gd=new GenerateRandomID();
System.out.println("Generated random String is :"+gd.generateRandomID());

In the above code, we are creating java.util.Random class instance with the current timestamp. This will insure that every time it's created, it will have a different instance. The method nextInt( ) will return a pseudorandom, uniformly distributed int value between 0 and the specified value. Using the above class and method, we created an integer index, which we will add to 48 or 97 since ASCII value of 0-9 is 48-57 and for a-z it is 97-122 .This addition to ASCII value decide which character(alphabet or numeric) is used in building 5 character long alphanumeric string. The ID_SIZE decides the length of the string and how many time while loop runs to decide each character of string. The NUM_OF_CHARS  is the total number of character range(0-9 and a-z have total 36 characters).


C:\>java GenerateRandomID
Generated random String is : mj2wf                                                                                        

Download Source Code



Posted on: May 26, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Random alpha numeric string of fixed size  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image