random class in java for string code example
Example 1: generate random string in java
import java.util.Random;
public class Generator {
public static String generateRandomPassword(int len) {
String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijk"
+"lmnopqrstuvwxyz!@#$%&";
Random rnd = new Random();
StringBuilder sb = new StringBuilder(len);
for (int i = 0; i < len; i++)
sb.append(chars.charAt(rnd.nextInt(chars.length())));
return sb.toString();
}
}
Example 2: java random between two strings
import java.util.Random;
public class RandomSelect {
public static void main (String [] args) {
String [] arr = {"A", "B", "C", "D"};
Random random = new Random();
int select = random.nextInt(arr.length);
System.out.println("Random String selected: " + arr[select]);
}
}