Java Random String randomString(int length)

Here you can find the source of randomString(int length)

Description

Returns a random String of numbers and letters (lower and upper case) of the specified length.

License

Open Source License

Parameter

Parameter Description
length the desired length of the random String to return.

Return

a random String of numbers and letters of the specified length.

Declaration

public static final String randomString(int length) 

Method Source Code

//package com.java2s;
/**/*from   w w  w  .  ja  v  a 2s.c o  m*/
 * $RCSfile: StringUtils.java,v $
 * $Revision: 1.1.1.1 $
 * $Date: 2002/09/09 13:51:15 $
 *
 * New Jive  from Jdon.com.
 *
 * This software is the proprietary information of CoolServlets, Inc.
 * Use is subject to license terms.
 */

import java.util.*;

public class Main {
    /**
     * Pseudo-random number generator object for use with randomString().
     * The Random class is not considered to be cryptographically secure, so
     * only use these random Strings for low to medium security applications.
     */
    private static Random randGen = new Random();
    /**
     * Array of numbers and letters of mixed case. Numbers appear in the list
     * twice so that there is a more equal chance that a number will be picked.
     * We can use the array to get a random number or letter by picking a random
     * array index.
     */
    private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
            + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();

    /**
     * Returns a random String of numbers and letters (lower and upper case)
     * of the specified length. The method uses the Random class that is
     * built-in to Java which is suitable for low to medium grade security uses.
     * This means that the output is only pseudo random, i.e., each number is
     * mathematically generated so is not truly random.<p>
     *
     * The specified length must be at least one. If not, the method will return
     * null.
     *
     * @param length the desired length of the random String to return.
     * @return a random String of numbers and letters of the specified length.
     */
    public static final String randomString(int length) {
        if (length < 1) {
            return null;
        }
        // Create a char buffer to put random letters and numbers in.
        char[] randBuffer = new char[length];
        for (int i = 0; i < randBuffer.length; i++) {
            randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
        }
        return new String(randBuffer);
    }
}

Related

  1. randomString(int length)
  2. randomString(int length)
  3. randomString(int length)
  4. randomString(int length)
  5. randomString(int length)
  6. randomstring(int lo, int hi)
  7. randomString(int stringLength)
  8. randomString(Integer len)
  9. randomString(Random r, int minCount, int maxCount)