Creates random string whose length is the number of characters specified. - Java java.util

Java examples for java.util:Random String

Description

Creates random string whose length is the number of characters specified.

Demo Code


import java.util.Random;

public class Main{
    protected static final Random rnd = new Random();
    /**/*from   w w w.  j  ava  2s  .co  m*/
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the set of characters whose ASCII value is
     * between <code>32</code> and <code>126</code> (inclusive).
     */
    public static String randomAscii(int count) {
        return random(count, (char) 32, (char) 126);
    }
    /**
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the set of characters specified.
     */
    public static String random(int count, char[] chars) {
        if (count == 0 || chars == null) {
            return StringUtil.EMPTY_STRING;
        }
        char[] result = new char[count];
        while (count-- > 0) {
            result[count] = chars[rnd.nextInt(chars.length)];
        }
        return new String(result);
    }
    /**
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the set of characters specified.
     */
    public static String random(int count, String chars) {
        if (chars == null) {
            return StringUtil.EMPTY_STRING;
        }
        return random(count, chars.toCharArray());
    }
    /**
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the provided range.
     */
    public static String random(int count, char start, char end) {
        if (count == 0) {
            return StringUtil.EMPTY_STRING;
        }
        char[] result = new char[count];
        int len = end - start + 1;
        while (count-- > 0) {
            result[count] = (char) (rnd.nextInt(len) + start);
        }
        return new String(result);
    }
}

Related Tutorials