Java Random String getRandomString(int length)

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

Description

Generates a random string.

License

Open Source License

Parameter

Parameter Description
length Length of string to be generated

Return

random string

Declaration

protected static String getRandomString(int length) 

Method Source Code

//package com.java2s;
/*//from   ww w.  j av a  2s  .  c  o m
 * LTIToolProvider - Classes to handle connections with an LTI 1 compliant tool consumer
 *     Copyright (C) 2013  Stephen P Vickers
 *
 *     This program is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU Lesser General Public License as published by
 *     the Free Software Foundation; either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Lesser General Public License for more details.
 *
 *     You should have received a copy of the GNU Lesser General Public License along
 *     with this program; if not, see <http://www.gnu.org/licences/>
 *
 *     Contact: stephen@spvsoftwareproducts.com
 */

import java.util.Random;

public class Main {
    /**
     * Generates a random string.
     * <p>
     * The generated string will only comprise letters (upper- and lower-case) and digits.
     *
     * @param length Length of string to be generated
     * @return random string
     */
    protected static String getRandomString(int length) {

        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        Random rand = new Random();
        StringBuilder value = new StringBuilder();
        int charsLength = chars.length() - 1;

        for (int i = 0; i < length; i++) {
            value.append(chars.charAt(rand.nextInt(charsLength)));
        }

        return value.toString();

    }
}

Related

  1. getRandomString(int lenght)
  2. getRandomString(int length)
  3. getRandomString(int length)
  4. getRandomString(int length)
  5. getRandomString(int length)
  6. getRandomString(int length)
  7. getRandomString(int length)
  8. getRandomString(int length)
  9. getRandomString(int length)