Java Random Int randomString(int length)

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

Description

Generate a random string of characters - including numbers

License

Open Source License

Parameter

Parameter Description
length the length of the string to return

Return

a random string of characters

Declaration

private static String randomString(int length) 

Method Source Code

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

public class Main {
    /**//from   w  ww  .ja  va 2  s .  c  o  m
     * Generate a random string of characters - including numbers
     *
     * @param length the length of the string to return
     * @return a random string of characters
     */
    private static String randomString(int length) {
        StringBuffer b = new StringBuffer(length);

        for (int i = 0; i < length; i++) {
            b.append(randomAlpha());
        }

        return b.toString();
    }

    /**
     * Generate a random character from the alphabet - either a-z or A-Z
     *
     * @return a random alphabetic character
     */
    private static char randomAlpha() {
        int i = (int) (Math.random() * 52);

        if (i > 25)
            return (char) (97 + i - 26);
        else
            return (char) (65 + i);
    }
}

Related

  1. randomSize(int maxValue)
  2. randomSMSCode(int length)
  3. randomStr(int length)
  4. randomStr(int length, String charSet)
  5. randomString(int count)
  6. randomString(int length)
  7. randomString(int length)
  8. randomString(int length)
  9. randomString(int min, int max)