|
How to generate a Random String in Java
The following example shows generating a random string in java.
|
package com.bethecoder.articles.basics.random;
import java.util.Random;
public class RandomStringTest {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(getRandomString(6));
System.out.println(getRandomString("123", 6));
System.out.println(getRandomString("xyz", 8));
System.out.println(getRandomString("abc123", 8));
}
public static String getRandomString(int length) {
return getRandomString("abcdefghijklmnopqrstuvwxyz", length);
}
public static String getRandomString(String allowedChars, int length) {
if (allowedChars == null || allowedChars.trim().length() == 0 || length <= 0) {
throw new IllegalArgumentException("Please provide valid input");
}
Random rand = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < length ; i ++) {
sb.append(allowedChars.charAt(rand.nextInt(allowedChars.length())));
}
return sb.toString();
}
}
|
| |
It gives the following output,
snammo
132121
yxxzyxzx
aabbc21a
|
|