Java Random String getRandomString()

Here you can find the source of getRandomString()

Description

get Random String

License

Apache License

Declaration

public static String getRandomString() 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.util.Random;

public class Main {
    private static char[] chs = { '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', '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 int DEFAULT_LEN = 6;
    private static int CHS_LEN = chs.length;

    public static String getRandomString() {
        return getRandomString(DEFAULT_LEN);
    }/*from  w w  w.j a  v a 2 s  .c  o m*/

    public static String getRandomString(int n) {
        if (n <= 0)
            n = DEFAULT_LEN;
        Random rand = new Random();
        StringBuilder rString = new StringBuilder();
        for (int i = 0; i < n; i++) {
            int j = rand.nextInt(CHS_LEN);
            rString.append(chs[j]);
        }
        return rString.toString();
    }
}

Related

  1. getRandomString()
  2. getRandomString()
  3. getRandomString()
  4. getRandomString()
  5. getRandomString()
  6. getRandomString()
  7. getRandomString(final int len)
  8. getRandomString(final int len)
  9. getRandomString(final int length)