Java Random String getRandomString()

Here you can find the source of getRandomString()

Description

Returns a randomly generated string of up to 15 characters.

License

Open Source License

Return

A randomly generated string

Declaration

public static String getRandomString() 

Method Source Code

//package com.java2s;
// The MIT License

import java.util.Random;

public class Main {
    private static final Random RAND = new Random();

    /**//from   w  w  w  .j a  v  a 2 s.co  m
     * Returns a randomly generated string of up to 15 characters.<br><br>
     *
     * @return A randomly generated string
     */
    public static String getRandomString() {
        return getRandomString(15);
    }

    /**
     * Returns a randomly generated string of up to X characters.<br><br>
     *
     * @param numChars the number of characters long the random string should be
     *
     * @return A randomly generated string
     */
    public static String getRandomString(int numChars) {
        int chars = RAND.nextInt(numChars);
        while (chars == 0)
            chars = RAND.nextInt(numChars);
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < chars; i++) {
            int index = 97 + RAND.nextInt(26);
            char c = (char) index;
            sb.append(c);
        } // for
        return sb.toString();
    }
}

Related

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