Java Password Generate generateString(int maxlength)

Here you can find the source of generateString(int maxlength)

Description

Generate a random string of a maximum length.

License

Open Source License

Parameter

Parameter Description
maxlength the maximum length of the string to generate

Return

the random string

Declaration

public static String generateString(int maxlength) 

Method Source Code

//package com.java2s;

import java.util.Random;

public class Main {
    /**/*ww w.  j a  v  a  2 s. c o m*/
     * Generate a random string.
     * 
     * @return the random string
     */
    public static String generateString() {
        Random r = new Random();
        return Long.toString(Math.abs(r.nextLong()), 36);
    }

    /**
     * Generate a random string of a maximum length. For strings of length 1,
     * generate a random lowercase letter a-z.
     * 
     * @param maxlength the maximum length of the string to generate
     * 
     * @return the random string
     */
    public static String generateString(int maxlength) {
        String s = null;
        Random r = new Random();
        if (maxlength == 1) {
            // Generate a random number between 97 and 122, inclusive.
            int n = 97 + r.nextInt(26);
            // Convert the number to a lowercase Unicode letter (x61-x7A).
            char c = (char) n;
            s = Character.toString(c);
        } else {
            s = Long.toString(Math.abs(r.nextLong()), 36);
            // Truncate the string to the maximum length if necessary.
            if (s.length() > maxlength) {
                s = s.substring(0, maxlength);
            }
        }
        return s;
    }
}

Related

  1. generateString(int length)
  2. generateString(int length)
  3. generateString(int length)
  4. generateString(int length)
  5. GenerateString(int Length)
  6. generateString(String alphabet, int length)
  7. generateString(String charSet, int len)
  8. generateStrings(int count, int length)
  9. generateStringsEntries(int cnt)