Java Random String randomString(int length)

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

Description

Generates a random string of length length, containing a-z, A-Z, 0-9

License

Open Source License

Declaration

public static String randomString(int length) 

Method Source Code

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

import java.util.*;

public class Main {
    public static final char[] CHARACTERS = { //indexes
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //0-7
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //8-15
            'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', //16-23
            'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', //24-31
            'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', //32-39
            'o', 'p', 'q', 'r', 's', 't', 'u', 'v', //40-47
            'w', 'x', 'y', 'z', '0', '1', '2', '3', //48-55
            '4', '5', '6', '7', '8', '9' //56-61
    };//from   ww  w.j  a  va2s  . c om

    /**
     * Generates a random string of length length,
     * containing a-z, A-Z, 0-9
     * 
     */
    public static String randomString(int length) {
        return getRandomString(length);
    }

    /**
     * Generates a random string of length length,
     * containing a-z, A-Z, 0-9
     * 
     */
    public static String getRandomString(int length) {
        Random generator = new Random();
        char str[] = new char[length];
        for (int i = 0; i < length; i++) {
            str[i] = CHARACTERS[generator.nextInt(CHARACTERS.length)];
        }
        return new String(str);
    }
}

Related

  1. randomString(final int length)
  2. randomString(int len)
  3. randomString(int length)
  4. randomString(int length)
  5. randomString(int length)
  6. randomString(int length)
  7. randomString(int length)
  8. randomstring(int lo, int hi)
  9. randomString(int stringLength)