Java Random String genRandomString(final int length)

Here you can find the source of genRandomString(final int length)

Description

gen Random String

License

Apache License

Declaration

public static String genRandomString(final int length) 

Method Source Code

//package com.java2s;
/*// w ww .ja  v  a2s.c  om
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 {
    private static final byte[] ALPHABETS = { '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' };

    public static String genRandomString(final int length) {
        byte[] data = new byte[length];
        for (int i = 0; i < data.length; i++) {
            data[i] = pickupAlphabet();
        }
        return new String(data);
    }

    private static byte pickupAlphabet() {
        int idx = new Random().nextInt(ALPHABETS.length);
        return ALPHABETS[idx];
    }
}

Related

  1. generateRandomString(Random random, int length)
  2. generateRandomString(Random random, int size)
  3. generateRandomString(Random rnd, char[] alphabet, int maxLength)
  4. generateRandomString(String str, int length)
  5. genRandomString()
  6. genRandomString(int count)
  7. getDefaultRandomName(String namePrefix)
  8. getRandomAString(int min, int max)
  9. getRandomColors(final int size, final List colors)