Creates a random alphabet string - Android java.util

Android examples for java.util:Random String

Description

Creates a random alphabet string

Demo Code

import java.util.Random;

public class Main{

    /**// w w w.  ja v  a2s .co  m
     * Creates a random alphabet string.
     * 
     * @param The length of random string.
     * @return Random string.
     */
    public static String randomAlphabetic(int length) {
        if (length == 0) {
            return "";
        } else if (length < 0) {
            throw new IllegalArgumentException(
                    "Specified random string length " + length
                            + " is negative.");
        }

        char[] buffer = new char[length];

        final char START = 'A';
        final char END = 'z';
        final int GAP = END - START + 1;
        char c = 0;

        for (int i = 0; i < length;) {
            c = (char) (random.nextInt(GAP) + START);
            if (('A' <= c) && (c <= 'Z') || ('a' <= c) && (c <= 'z')) {
                buffer[i] = c;
                ++i;
            } else {
                ;
            }
        }

        return new String(buffer);
    }

}

Related Tutorials