Java Random String getRandomString(int len)

Here you can find the source of getRandomString(int len)

Description

A random lower case string

License

Open Source License

Parameter

Parameter Description
len a parameter

Declaration

public static String getRandomString(int len) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Random;

public class Main {
    private static final char[] consonants = "bcdfghjklmnpqrstvwxz".toCharArray();
    /**//  ww w  . j  av  a  2s.c  o  m
     * Note Random is thread safe. Is using it across threads a bottleneck? If
     * you need repeatable results, you should create your own Random where you
     * can control both the seed and the usage.
     */
    private static final Random r = new Random();
    private static final char[] vowels = "aeiouy".toCharArray();

    /**
     * A random lower case string
     * 
     * @param len
     * @return
     */
    public static String getRandomString(int len) {
        Random rnd = getRandom();
        char[] s = new char[len];
        for (int i = 0; i < len; i++) {
            // roughly consonant-consonant-vowel for pronounceability
            char c;
            if (rnd.nextInt(3) == 0) {
                c = vowels[rnd.nextInt(vowels.length)];
            } else {
                c = consonants[rnd.nextInt(consonants.length)];
            }
            s[i] = c;
        }
        return new String(s);
    }

    /**
     * @return a Random instance for generating random numbers. This is to avoid
     *         generating new Random instances for each number as the results
     *         aren't well distributed.
     *         <p>
     *         If you need repeatable results, you should create your own
     *         Random.
     *         <p>
     *         Note: Java's Random <i>is</i> thread safe, and can be used by
     *         many threads - although for high simultaneous usage, you may wish
     *         to create your own Randoms.
     */
    public static Random getRandom() {
        return r;
    }
}

Related

  1. getRandomString(final int length)
  2. getRandomString(final int size)
  3. getRandomString(final int size)
  4. getRandomString(int cantidad, boolean mayusculas, boolean minusculas, boolean numeros, boolean simbolos, boolean repetir)
  5. getRandomString(int count)
  6. getRandomString(int len)
  7. getRandomString(int len)
  8. getRandomString(int len)
  9. getRandomString(int len, boolean ascii_only)