Generating a Random String in Java

I have had a need to create a string in java. I wanted it to be clearly a string, and thus, I decided to make it all lower cases, with spaces. This is the resulting code, inspired by some googling, but since I found nothing for exactly what I wanted, I include it here:

/** In tests, I prefer my random numbers to be identical on identical runs. **/
private static Random rnd = new Random(123456789L);
private static String raw = "abcdefghijklmnoprstu ";
private String randomStr() {
    // if you want the probability of duplication to be small for 10^n iterations of this
    // code, then replace 4 with n.
    char[] chars = new char[4 + rnd.nextInt(50)];
    for (int i = 0; i < chars.length ;i++) {
        chars[i] = raw.charAt(rnd.nextInt(raw.length()));
    }
    return new String(chars);
}

Leave a Reply

You must be logged in to post a comment.