Here you can find the source of randomString(int length)
Parameter | Description |
---|---|
length | the desired length of the random String to return. |
public static final String randomString(int length)
//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); } }