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
Must read : 5 programs to Generate random numbers in given specific range before java 7, in java 7 and java 8
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";
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