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 final String randomString(int length) 

Method Source Code

//package com.java2s;
/*//from   w  ww.  j  a va 2 s. c  o  m
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

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();

    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);
    }

    public static final String randomString(final String prefix, int length) {
        return (prefix + randomString(length));
    }
}

Related

  1. randomString()
  2. randomString(final int length)
  3. randomString(int len)
  4. randomString(int length)
  5. randomString(int length)
  6. randomString(int length)
  7. randomString(int length)
  8. randomString(int length)
  9. randomstring(int lo, int hi)