Java Random String genRandomString()

Here you can find the source of genRandomString()

Description

Generates a random String of up to 10 characters

License

Open Source License

Declaration

public static String genRandomString() 

Method Source Code


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

import java.util.Random;

public class Main {
    /**/*from   www  .  j  av  a 2  s.  c om*/
     * All the standard ASCII alphanumeric characters
     */
    private static final char[] ALPHANUM = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
            'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g',
            'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2',
            '3', '4', '5', '6', '7', '8', '9', '0'

    };
    /**
     * RNG
     */
    private static final Random rand = new Random();

    /**
     * Generates a random <code>String</code> of up to 10 characters
     *
     * @return {@link StringUtil#genRandomString(int)}
     * @see {@link StringUtil#genRandomString(int)}
     */
    public static String genRandomString() {
        return genRandomString(rand.nextInt(10));
    }

    /**
     * Generates a random <code>String</code> of the specified length
     *
     * @param len Length of the String
     * @return Random String
     */
    public static String genRandomString(final int len) {
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < len; i++) {
            final char c = ALPHANUM[rand.nextInt(ALPHANUM.length)];
            sb.append(c);
        }
        return sb.toString();
    }
}

Related

  1. generateRandomString(int wordsLength, String separator)
  2. generateRandomString(Random random, int length)
  3. generateRandomString(Random random, int size)
  4. generateRandomString(Random rnd, char[] alphabet, int maxLength)
  5. generateRandomString(String str, int length)
  6. genRandomString(final int length)
  7. genRandomString(int count)
  8. getDefaultRandomName(String namePrefix)
  9. getRandomAString(int min, int max)