Java Random String generateRandomCharacters(int N)

Here you can find the source of generateRandomCharacters(int N)

Description

Generates a random alpha-numeric character string of length N

License

Open Source License

Parameter

Parameter Description
N the length of the string

Declaration

public static String generateRandomCharacters(int N) 

Method Source Code

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

public class Main {
    private static String CHARS = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZabcdefghijklmnpqrstuvwxyz";
    private static String SYMBOLS_AND_CHARS = "{|}~!#$%&()*+,-.:;<=>?@[]^_" + CHARS;

    /**/*from   w ww.  j a v a2 s .c  om*/
     * Generates a random alpha-numeric character string of length N
     * @param N the length of the string
     * @return
     */
    public static String generateRandomCharacters(int N) {
        return generateRandomCharacters(N, false);
    }

    public static String generateRandomCharacters(int N, boolean includeSymbols) {
        StringBuilder sbuilder = new StringBuilder();
        for (int index = 0; index < N; index++) {
            sbuilder.append(randomCharacter(includeSymbols));
        }
        return sbuilder.toString();
    }

    public static char randomCharacter(boolean includeSymbols) {
        if (includeSymbols) {
            int ival = (int) (Math.random() * SYMBOLS_AND_CHARS.length());
            return SYMBOLS_AND_CHARS.charAt(ival);
        } else {
            int ival = (int) (Math.random() * CHARS.length());
            return CHARS.charAt(ival);
        }
    }
}

Related

  1. createRandomString(int length)
  2. createRandomWord(boolean startWithCapital)
  3. generateRandom(int num)
  4. generateRandom(Integer digits)
  5. generateRandomChain(int length)
  6. generateRandomCode()
  7. generateRandomSentence()
  8. generateRandomStr(final int length)
  9. generateRandomStr(int length)