Java Random String generateRandomString()

Here you can find the source of generateRandomString()

Description

Generate random String , get its length , generate char list and append to random string generated.

License

Apache License

Return

generate String

Declaration

public static String generateRandomString() 

Method Source Code

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

import java.util.Random;

public class Main {
    private static final String CHAR_LIST = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    private static final int RANDOM_STRING_LENGTH = 10;

    /**/*from w w  w .  ja v a  2s .c  o  m*/
     * Generate random String , get its length , generate char list and append
     * to random string generated.
     *
     * @return generate String
     * @see StringUtil#getRandomNumber()
     */
    public static String generateRandomString() {
        StringBuffer strBfrRandom = new StringBuffer();
        for (int i = 0; i < RANDOM_STRING_LENGTH; i++) {
            int intNumber = getRandomNumber();
            char character = CHAR_LIST.charAt(intNumber);
            strBfrRandom.append(character);
        }
        return strBfrRandom.toString();
    }

    /**
     * Generate random number
     *
     * @return random number
     */
    public static int getRandomNumber() {
        int intRandom = 0;
        Random rdmGenerator = new Random();
        intRandom = rdmGenerator.nextInt(CHAR_LIST.length());
        if (intRandom - 1 == -1) {
            return intRandom;
        } else {
            return intRandom - 1;
        }
    }
}

Related

  1. generateRandomStr(int length)
  2. generateRandomString()
  3. generateRandomString()
  4. generateRandomString()
  5. generateRandomString()
  6. generateRandomString()
  7. generateRandomString()
  8. generateRandomString(final int minCharLen, final int maxCharLen)
  9. generateRandomString(final String pattern)