Example to generate random alphanumeric string in java



In this we will write example program to generate random alphanumeric string in java.

Example 1 to generate random alphanumeric string in java using org.apache.commons.lang.
RandomStringUtils.randomAlphanumeric(int) >


Pass length of random alphanumeric string to be generated in randomAlphanumeric(int) method


import org.apache.commons.lang.RandomStringUtils;
public class GenerateAlphaNumericNumberUsingCommons {
public static void main(String[] args) {
     System.out.println( RandomStringUtils.randomAlphanumeric(6));
}
}
/*OUTPUT
Duu7L4
*/
In the above program 6 is length of random alphanumeric string to be generated.

Jar used in above program = commons-lang.jar




Example 2 to generate random alphanumeric string in java >
import java.util.Random;
public class GenerateAlphaNumericNumber {
public static void main(String[] args) {
     int lengthOfRandomString = 6;
     Random rand = new Random();
     String alphaNumericCharacters = "abcdefghijklmnopqrstuvwxyz"
              + "ABCDEFGHIJLMNOPQRSTUVWXYZ"
              + "1234567890";
     // Use StringBuilder in place of String to avoid unnecessary object formation
     StringBuilder result = new StringBuilder();
    
     for (int i =0; i< lengthOfRandomString ; i++) {
          result.append(
                       alphaNumericCharacters.
                            charAt(rand.nextInt(alphaNumericCharacters.length())));
     }
     System.out.println(result.toString());
}
}
/*OUTPUT
W9j11S
*/

In the above program 6 is length of random alphanumeric string to be generated.
And,
random alphanumeric string to be generated will contain characters from alphaNumericCharacters only.



RELATED LINKS>


Difference between String, StringBuffer and StringBuilder in java - In depth coverage

Labels: Core Java
eEdit
Must read for you :