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 final String AB = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final Random rnd = new Random();
    public static final int MIN_LEN = 1;
    public static final int MAX_LEN = 10;

    public static String getRandomString() {
        return getRandomString(MIN_LEN, MAX_LEN);
    }/*from   ww  w. ja v a 2  s.co m*/

    public static String getRandomString(int length) {
        return getRandomString(length, length);
    }

    public static String getRandomString(int minLength, int maxLength) {
        if (minLength < 1 || maxLength < 1)
            throw new IllegalArgumentException("minLength and maxLength must both me positive");
        if (minLength > maxLength)
            throw new IllegalArgumentException("minLength cannot be smaller than maxLength");

        int length = (minLength == maxLength) ? minLength : rnd.nextInt(maxLength - minLength + 1) + minLength;

        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            sb.append(AB.charAt(rnd.nextInt(AB.length())));
        }

        return sb.toString();
    }
}

Related

  1. getRandomStr(int n)
  2. getRandomStr(int qty)
  3. getRandomStr(String src)
  4. getRandomString()
  5. getRandomString()
  6. getRandomString()
  7. getRandomString()
  8. getRandomString()
  9. getRandomString()