Online Training Spring Hibernate Training in Delhi R Programming Training Course Big Data and Hadoop Training Java Training

Random alpha numeric string of fixed size

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

Ads

Tutorials   
How to read properties file in Java? Generate random numbers in Java Cloneable Interface in Java What is the flaw with the Stack class? List In Java Java Stack Example HashSet In Java Enumeration in java How to generate random number in java Iterator in java Queue in java Transient Java Keyword clone method in Java Java Queue example Logger in Java Java current date - How to get current date in Java Collection : LinkedList Example Collection : ArrayList Example Random alpha numeric string of fixed size Java List Iterator Example The Hashtable Class The BitSet class Java Vector Java Enumeration Data Structures in Java Java Transient Variable Java Date Format Example Java Properties File Example Map.Entry Java Interface Java Property File java preferences,Change the value of Preferences by user Retrieving a Preference Node Java hasNext Write Keys and Values to the Properties file in Java Get All Keys and Values of the Properties files in Java Properties file in Java Properties file in Java Determining If a Preference Node Contains a Specific Value Change the value of Preferences by user Clone method example in Java Implementing a Simple Event Notifier Determining When a Preference Node Is Added or Removed Listening for Changes to Preference Values in a Preference Node Importing Preferences Finding a Preference in a Preference Tree Retrieving the Parent and Child Nodes of a Preference Node Determining If a Preference Node Exists Removing a Preference Node Creating a Preference Node Getting the Maximum Size of a Preference Key and Value
Ads

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 :

EXAMPLE 1

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));
//System.out.println(grs.getAlphaNumeric(20));
}

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());
sb.append(ALPHA_NUM.charAt(ndx));
}
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.

OUTPUT

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

EXAMPLE 2

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));
}
x++;
}

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).

OUTPUT

C:\>java GenerateRandomID
Index=22
Index=19
Index=2
Index=32
Index=15
Generated random String is : mj2wf                                                                                        

Download Source Code

Advertisements

Share on Google+Share on Google+

Random alpha numeric string of fixed size

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

Advertisements

Ads
 

Discuss: Random alpha numeric string of fixed size  

Post your Comment


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

Ads

 

Ads