Java Random String getRandomString(int length)

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

Description

get the alphanumeric string with the specific length.

License

Open Source License

Parameter

Parameter Description
length the length which is 8 by default.

Declaration

public static String getRandomString(int length) 

Method Source Code


//package com.java2s;
import java.util.Random;

public class Main {
    static char[] m_alphanumeric = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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' };
    private static Random random = new Random();

    /**//from   w  w w  .j a  v  a2 s.  co  m
     * get the alphanumeric string with the specific length.
     * @param length the length which is 8 by default.
     */
    public static String getRandomString(int length) {
        if (length <= 0)
            length = 8;
        byte[] bytes = new byte[length];
        random.nextBytes(bytes);
        StringBuffer sb = new StringBuffer(length);
        for (int i = 0; i < length; i++) {
            sb.append(m_alphanumeric[Math.abs(bytes[i] % 36)]);
        }
        return sb.toString();
    }
}

Related

  1. getRandomString(int len, boolean ascii_only)
  2. getRandomString(int lenght)
  3. getRandomString(int length)
  4. getRandomString(int length)
  5. getRandomString(int length)
  6. getRandomString(int length)
  7. getRandomString(int length)
  8. getRandomString(int length)
  9. getRandomString(int length)