Java Random String getRandomString(int randomPasswordLength)

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

Description

Generate random string for password

License

Open Source License

Parameter

Parameter Description
randomPasswordLength Length

Return

Random string of specified length

Declaration

public static String getRandomString(int randomPasswordLength) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Random;

public class Main {
    private static final String RANDOM_PATTERN = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /**/*from   w w  w  . j  a  v  a2s .co m*/
     * Generate random string for password
     *
     * @param randomPasswordLength
     *            Length
     * @return Random string of specified length
     */
    public static String getRandomString(int randomPasswordLength) {
        return getRandomString(randomPasswordLength, RANDOM_PATTERN);
    }

    /**
     * Generate random string for password consisting of specified chars
     *
     * @param randomPasswordLength
     *            Length
     * @param characters
     *            String defining characters to use
     * @return Random string of specified length containing specified characters
     *         only
     */
    public static String getRandomString(int randomPasswordLength, String characters) {
        Random rng = new Random();

        char[] text = new char[randomPasswordLength];
        for (int i = 0; i < randomPasswordLength; ++i) {
            text[i] = characters.charAt(rng.nextInt(characters.length()));
        }
        return new String(text);
    }
}

Related

  1. getRandomString(int length)
  2. getRandomString(int length, Random rnd)
  3. getRandomString(int length, String charset)
  4. getRandomString(int min, int max)
  5. getRandomString(int minLength, int maxLength)
  6. getRandomString(int size)
  7. getRandomString(int size)
  8. getRandomString(int size)
  9. getRandomString(int size)