Java Random String randomString(int length)

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

Description

random String

License

Open Source License

Declaration

public static String randomString(int length) 

Method Source Code

//package com.java2s;
/*/*from   w  w  w . j  av a  2 s  . co m*/
 * @(#)Util.java        1.00 2005/03/16
 * @author  Denny
 * Copyright (c) 1994-2005 Teansun, Inc.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of Teamsun, Inc.
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with Teamsun.
 *
 */

import java.util.*;

public class Main {
    private static Random randGen = null;
    private static char[] numbersAndLetters = null;
    private static Object initLock = new Object();

    public static String randomString(int length) {
        if (length < 1) {
            return null;
        }

        if (randGen == null) {
            synchronized (initLock) {
                if (randGen == null) {
                    randGen = new Random();
                    numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz"
                            + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
                }
            }
        }

        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. randomRealisticUnicodeString(Random r)
  2. randomString()
  3. randomString()
  4. randomString(final int length)
  5. randomString(int len)
  6. randomString(int length)
  7. randomString(int length)
  8. randomString(int length)
  9. randomString(int length)