Java Random String randomString(int length)

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

Description

randomString(...) method returns a string of specific length based on random characters.

License

Open Source License

Parameter

Parameter Description
length a parameter

Return

String value of the string

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 {
    /**/*w  ww  . jav a  2  s.com*/
     * randomString(...) method returns a string of specific length based on
     * random characters.
     * <p>
     * adapted from
     * http://stackoverflow.com/questions/5683327/how-to-generate-a-random-string-of-20-characters
     * <p>
     * msdn
     * http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
     * file special chars < > : " / \ | ? *
     *
     * @param length
     * @return <code>String</code> value of the string
     */
    public static String randomString(int length) {
        char[] chars = "ab1@cd2#ef3$gh4%ij5^kl6&mn7_op8-qr9?st0~uv3~wx7!yz".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }

        return sb.toString();
    }
}

Related

  1. randomString()
  2. randomString()
  3. randomString(final int length)
  4. randomString(int len)
  5. randomString(int length)
  6. randomString(int length)
  7. randomString(int length)
  8. randomString(int length)
  9. randomString(int length)