Java Random String getRandomString(int length)

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

Description

Generates a random name, generated with java.util.Random and an Alphabet of 0-9,a-z,A-Z
e.g.

License

Apache License

Parameter

Parameter Description
length Length of the returned String

Return

a randomly generated String consisting of a-z,A-Z and 0-9

Declaration


public static String getRandomString(int length) 

Method Source Code

//package com.java2s;
/**  /*w ww  .  j  a v a2s.  co m*/
 *  Copyright 2013 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License. 
 *
 */

import java.util.Random;

public class Main {
    /**
     * Generates a random name, generated with {@link java.util.Random} and an Alphabet of 0-9,a-z,A-Z <br/>
     * e.g. for the Mailbox
     * 
     * @param length
     *            Length of the returned String
     * @return a randomly generated String consisting of a-z,A-Z and 0-9
     */

    public static String getRandomString(int length) {
        char[] values = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
                's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
                'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5',
                '6', '7', '8', '9' };

        Random random = new Random();
        StringBuffer stringBuf = new StringBuffer();
        for (int i = 0; i < length; i++) {
            // generates a random number and stores it in the stringbuffer
            stringBuf.append(values[Math.abs(random.nextInt()) % (values.length)]);

        }
        return stringBuf.toString();
    }
}

Related

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