<p>I've been looking for a <em>simple</em> Java algorithm to generate a pseudo-random alpha-numeric string.  In my situation it would be used as a unique session/key identifier that would "likely" be unique over <code>500K+</code> generation (my needs don't really require anything much more sophisticated).  </p>

<p>Ideally, I would be able to specify a length depending on my uniqueness needs. For example, a generated string of length 12 might look something like <code>"AEYGF7K0DM1X"</code>.  </p>

[{'answer_id': 41156, 'author': 'erickson', 'author_id': 3474, 'author_profile': 'https://Stackoverflow.com/users/3474', 'pm_score': 12, 'selected': True, 'text': '<h2>Algorithm</h2>\n<p>To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.</p>\n<h2>Implementation</h2>\n<p>Here\'s some fairly simple and very flexible code for generating random identifiers. <em>Read the information that follows</em> for important application notes.</p>\n<pre><code>public class RandomString {\n\n    /**\n     * Generate a random string.\n     */\n    public String nextString() {\n        for (int idx = 0; idx &lt; buf.length; ++idx)\n            buf[idx] = symbols[random.nextInt(symbols.length)];\n        return new String(buf);\n    }\n\n    public static final String upper = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;\n\n    public static final String lower = upper.toLowerCase(Locale.ROOT);\n\n    public static final String digits = &quot;0123456789&quot;;\n\n    public static final String alphanum = upper + lower + digits;\n\n    private final Random random;\n\n    private final char[] symbols;\n\n    private final char[] buf;\n\n    public RandomString(int length, Random random, String symbols) {\n        if (length &lt; 1) throw new IllegalArgumentException();\n        if (symbols.length() &lt; 2) throw new IllegalArgumentException();\n        this.random = Objects.requireNonNull(random);\n        this.symbols = symbols.toCharArray();\n        this.buf = new char[length];\n    }\n\n    /**\n     * Create an alphanumeric string generator.\n     */\n    public RandomString(int length, Random random) {\n        this(length, random, alphanum);\n    }\n\n    /**\n     * Create an alphanumeric strings from a secure generator.\n     */\n    public RandomString(int length) {\n        this(length, new SecureRandom());\n    }\n\n    /**\n     * Create session identifiers.\n     */\n    public RandomString() {\n        this(21);\n    }\n\n}\n</code></pre>\n<h2>Usage examples</h2>\n<p>Create an insecure generator for 8-character identifiers:</p>\n<pre><code>RandomString gen = new RandomString(8, ThreadLocalRandom.current());\n</code></pre>\n<p>Create a secure generator for session identifiers:</p>\n<pre><code>RandomString session = new RandomString();\n</code></pre>\n<p>Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:</p>\n<pre><code>String easy = RandomString.digits + &quot;ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx&quot;;\nRandomString tickets = new RandomString(23, new SecureRandom(), easy);\n</code></pre>\n<h2>Use as session identifiers</h2>\n<p>Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.</p>\n<p>There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.</p>\n<p>The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.</p>\n<h2>Use as object identifiers</h2>\n<p>Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.</p>\n<p>Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.</p>\n<p>Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as &quot;the birthday paradox.&quot; <a href="https://en.wikipedia.org/wiki/Birthday_problem#Square_approximation" rel="noreferrer">The probability of a collision,</a> <em>p</em>, is approximately n<sup>2</sup>/(2q<sup>x</sup>), where <em>n</em> is the number of identifiers actually generated, <em>q</em> is the number of distinct symbols in the alphabet, and <em>x</em> is the length of the identifiers. This should be a very small number, like 2<sup>‑50</sup> or less.</p>\n<p>Working this out shows that the chance of collision among 500k 15-character identifiers is about 2<sup>‑52</sup>, which is probably less likely than undetected errors from cosmic rays, etc.</p>\n<h2>Comparison with UUIDs</h2>\n<p>According to their specification, <a href="https://www.rfc-editor.org/rfc/rfc4122#section-6" rel="noreferrer">UUIDs</a> are not designed to be unpredictable, and <em>should not</em> be used as session identifiers.</p>\n<p>UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a &quot;random&quot; UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.</p>\n<p>UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.</p>\n'}, {'answer_id': 41177, 'author': 'Apocalisp', 'author_id': 3434, 'author_profile': 'https://Stackoverflow.com/users/3434', 'pm_score': 5, 'selected': False, 'text': "<p>Here it is in Java:</p>\n\n<pre><code>import static java.lang.Math.round;\nimport static java.lang.Math.random;\nimport static java.lang.Math.pow;\nimport static java.lang.Math.abs;\nimport static java.lang.Math.min;\nimport static org.apache.commons.lang.StringUtils.leftPad\n\npublic class RandomAlphaNum {\n  public static String gen(int length) {\n    StringBuffer sb = new StringBuffer();\n    for (int i = length; i &gt; 0; i -= 12) {\n      int n = min(12, abs(i));\n      sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36), n, '0'));\n    }\n    return sb.toString();\n  }\n}\n</code></pre>\n\n<p>Here's a sample run:</p>\n\n<pre><code>scala&gt; RandomAlphaNum.gen(42)\nres3: java.lang.String = uja6snx21bswf9t89s00bxssu8g6qlu16ffzqaxxoy\n</code></pre>\n"}, {'answer_id': 41762, 'author': 'Steve McLeod', 'author_id': 2959, 'author_profile': 'https://Stackoverflow.com/users/2959', 'pm_score': 10, 'selected': False, 'text': '<p>Java supplies a way of doing this directly. If you don\'t want the dashes, they are easy to strip out. Just use <code>uuid.replace(&quot;-&quot;, &quot;&quot;)</code></p>\n<pre><code>import java.util.UUID;\n\npublic class randomStringGenerator {\n    public static void main(String[] args) {\n        System.out.println(generateString());\n    }\n\n    public static String generateString() {\n        String uuid = UUID.randomUUID().toString();\n        return &quot;uuid = &quot; + uuid;\n    }\n}\n</code></pre>\n<h3>Output</h3>\n<pre class="lang-none prettyprint-override"><code>uuid = 2d7428a6-b58c-4008-8575-f05549f16316\n</code></pre>\n'}, {'answer_id': 41772, 'author': 'Todd', 'author_id': 3803, 'author_profile': 'https://Stackoverflow.com/users/3803', 'pm_score': 3, 'selected': False, 'text': '<p>I found this solution that generates a random hex encoded string.  The provided unit test seems to hold up to my primary use case.  Although, it is slightly more complex than some of the other answers provided.</p>\n\n<pre><code>/**\n * Generate a random hex encoded string token of the specified length\n *  \n * @param length\n * @return random hex string\n */\npublic static synchronized String generateUniqueToken(Integer length){ \n    byte random[] = new byte[length];\n    Random randomGenerator = new Random();\n    StringBuffer buffer = new StringBuffer();\n\n    randomGenerator.nextBytes(random);\n\n    for (int j = 0; j &lt; random.length; j++) {\n        byte b1 = (byte) ((random[j] &amp; 0xf0) &gt;&gt; 4);\n        byte b2 = (byte) (random[j] &amp; 0x0f);\n        if (b1 &lt; 10)\n            buffer.append((char) (\'0\' + b1));\n        else\n            buffer.append((char) (\'A\' + (b1 - 10)));\n        if (b2 &lt; 10)\n            buffer.append((char) (\'0\' + b2));\n        else\n            buffer.append((char) (\'A\' + (b2 - 10)));\n    }\n    return (buffer.toString());\n}\n\n@Test\npublic void testGenerateUniqueToken(){\n    Set set = new HashSet();\n    String token = null;\n    int size = 16;\n\n    /* Seems like we should be able to generate 500K tokens \n     * without a duplicate \n     */\n    for (int i=0; i&lt;500000; i++){\n        token = Utility.generateUniqueToken(size);\n\n        if (token.length() != size * 2){\n            fail("Incorrect length");\n        } else if (set.contains(token)) {\n            fail("Duplicate token generated");\n        } else{\n            set.add(token);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 43496, 'author': 'cmsherratt', 'author_id': 3512, 'author_profile': 'https://Stackoverflow.com/users/3512', 'pm_score': 9, 'selected': False, 'text': '<p>If you\'re happy to use Apache classes, you could use <a href="https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/RandomStringGenerator.html" rel="noreferrer"><code>org.apache.commons.text.RandomStringGenerator</code></a> (<a href="https://en.wikipedia.org/wiki/Apache_Commons#Commons_Proper" rel="noreferrer">Apache Commons Text</a>).</p>\n<p>Example:</p>\n<pre><code>RandomStringGenerator randomStringGenerator =\n        new RandomStringGenerator.Builder()\n                .withinRange(\'0\', \'z\')\n                .filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)\n                .build();\nrandomStringGenerator.generate(12); // toUpperCase() if you want\n</code></pre>\n<p>Since <a href="https://en.wikipedia.org/wiki/Apache_Commons#Commons_Proper" rel="noreferrer">Apache Commons Lang</a> 3.6, <code>RandomStringUtils</code> is deprecated.</p>\n'}, {'answer_id': 157202, 'author': 'maxp', 'author_id': 21152, 'author_profile': 'https://Stackoverflow.com/users/21152', 'pm_score': 9, 'selected': False, 'text': '<pre><code>static final String AB = &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&quot;;\nstatic SecureRandom rnd = new SecureRandom();\n\nString randomString(int len){\n   StringBuilder sb = new StringBuilder(len);\n   for(int i = 0; i &lt; len; i++)\n      sb.append(AB.charAt(rnd.nextInt(AB.length())));\n   return sb.toString();\n}\n</code></pre>\n'}, {'answer_id': 1016930, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I have developed an application to develop an autogenerated alphanumberic string for my project. In this string, the first three characters are alphabetical and the next seven are integers.</p>\n<pre><code>public class AlphaNumericGenerator {\n\n    public static void main(String[] args) {\n        java.util.Random r = new java.util.Random();\n        int i = 1, n = 0;\n        char c;\n        String str = &quot;&quot;;\n        for (int t = 0; t &lt; 3; t++) {\n            while (true) {\n                i = r.nextInt(10);\n                if (i &gt; 5 &amp;&amp; i &lt; 10) {\n\n                    if (i == 9) {\n                        i = 90;\n                        n = 90;\n                        break;\n                    }\n                    if (i != 90) {\n                        n = i * 10 + r.nextInt(10);\n                        while (n &lt; 65) {\n                            n = i * 10 + r.nextInt(10);\n                        }\n                    }\n                    break;\n                }\n            }\n            c = (char)n;\n\n            str = String.valueOf(c) + str;\n        }\n\n        while(true){\n            i = r.nextInt(10000000);\n            if(i &gt; 999999)\n                break;\n        }\n        str = str + i;\n        System.out.println(str);\n    }\n}\n</code></pre>\n'}, {'answer_id': 1439556, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 7, 'selected': False, 'text': '<p>In one line:</p>\n<pre><code>Long.toHexString(Double.doubleToLongBits(Math.random()));\n</code></pre>\n<p>Source: <em><a href="http://mynotes.wordpress.com/2009/07/23/java-generating-random-string/" rel="noreferrer">Java - generating a random string</a></em></p>\n'}, {'answer_id': 2178588, 'author': 'dfa', 'author_id': 89266, 'author_profile': 'https://Stackoverflow.com/users/89266', 'pm_score': 5, 'selected': False, 'text': '<p>Using <a href="https://bitbucket.org/adamldavis/dollar/" rel="nofollow noreferrer">Dollar</a> should be as simple as:</p>\n<pre><code>// &quot;0123456789&quot; + &quot;ABCDE...Z&quot;\nString validCharacters = $(\'0\', \'9\').join() + $(\'A\', \'Z\').join();\n\nString randomString(int length) {\n    return $(validCharacters).shuffle().slice(length).toString();\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n    for (int i : $(5)) {\n        System.out.println(randomString(12));\n    }\n}\n</code></pre>\n<p>It outputs something like this:</p>\n<pre class="lang-none prettyprint-override"><code>DKL1SBH9UJWC\nJH7P0IT21EA5\n5DTI72EO6SFU\nHQUMJTEBNF7Y\n1HCR6SKYWGT7\n</code></pre>\n'}, {'answer_id': 6530353, 'author': 'Suganya', 'author_id': 822390, 'author_profile': 'https://Stackoverflow.com/users/822390', 'pm_score': 3, 'selected': False, 'text': '<pre><code>import java.util.*;\nimport javax.swing.*;\n\npublic class alphanumeric {\n    public static void main(String args[]) {\n        String nval, lenval;\n        int n, len;\n\n        nval = JOptionPane.showInputDialog(&quot;Enter number of codes you require: &quot;);\n        n = Integer.parseInt(nval);\n\n        lenval = JOptionPane.showInputDialog(&quot;Enter code length you require: &quot;);\n        len = Integer.parseInt(lenval);\n\n        find(n, len);\n    }\n\n    public static void find(int n, int length) {\n        String str1 = &quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;\n        StringBuilder sb = new StringBuilder(length);\n        Random r = new Random();\n\n        System.out.println(&quot;\\n\\t Unique codes are \\n\\n&quot;);\n        for(int i=0; i&lt;n; i++) {\n            for(int j=0; j&lt;length; j++) {\n                sb.append(str1.charAt(r.nextInt(str1.length())));\n            }\n            System.out.println(&quot;  &quot; + sb.toString());\n            sb.delete(0, length);\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 7367588, 'author': 'michaelok', 'author_id': 443633, 'author_profile': 'https://Stackoverflow.com/users/443633', 'pm_score': 3, 'selected': False, 'text': '<p>You mention "simple", but just in case anyone else is looking for something that meets more stringent security requirements, you might want to take a look at <a href="https://github.com/zhelev/jpwgen" rel="nofollow noreferrer">jpwgen</a>.  jpwgen is modeled after <a href="http://sourceforge.net/projects/pwgen/" rel="nofollow noreferrer">pwgen</a> in Unix, and is very configurable.</p>\n'}, {'answer_id': 7816591, 'author': 'Jameskittu', 'author_id': 367407, 'author_profile': 'https://Stackoverflow.com/users/367407', 'pm_score': 3, 'selected': False, 'text': '<pre><code>import java.util.Date;\nimport java.util.Random;\n\npublic class RandomGenerator {\n\n  private static Random random = new Random((new Date()).getTime());\n\n    public static String generateRandomString(int length) {\n      char[] values = {\'a\',\'b\',\'c\',\'d\',\'e\',\'f\',\'g\',\'h\',\'i\',\'j\',\n               \'k\',\'l\',\'m\',\'n\',\'o\',\'p\',\'q\',\'r\',\'s\',\'t\',\n               \'u\',\'v\',\'w\',\'x\',\'y\',\'z\',\'0\',\'1\',\'2\',\'3\',\n               \'4\',\'5\',\'6\',\'7\',\'8\',\'9\'};\n\n      String out = "";\n\n      for (int i=0;i&lt;length;i++) {\n          int idx=random.nextInt(values.length);\n          out += values[idx];\n      }\n      return out;\n    }\n}\n</code></pre>\n'}, {'answer_id': 10177396, 'author': 'cmpbah', 'author_id': 1336707, 'author_profile': 'https://Stackoverflow.com/users/1336707', 'pm_score': 4, 'selected': False, 'text': '<pre><code>import java.util.Random;\n\npublic class passGen{\n    // Version 1.0\n    private static final String dCase = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\n    private static final String uCase = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;\n    private static final String sChar = &quot;!@#$%^&amp;*&quot;;\n    private static final String intChar = &quot;0123456789&quot;;\n    private static Random r = new Random();\n    private static StringBuilder pass = new StringBuilder();\n\n    public static void main (String[] args) {\n        System.out.println (&quot;Generating pass...&quot;);\n        while (pass.length () != 16){\n            int rPick = r.nextInt(4);\n            if (rPick == 0){\n                int spot = r.nextInt(26);\n                pass.append(dCase.charAt(spot));\n            } else if (rPick == 1) {\n                int spot = r.nextInt(26);\n                pass.append(uCase.charAt(spot));\n            } else if (rPick == 2) {\n                int spot = r.nextInt(8);\n                pass.append(sChar.charAt(spot));\n            } else {\n                int spot = r.nextInt(10);\n                pass.append(intChar.charAt(spot));\n            }\n        }\n        System.out.println (&quot;Generated Pass: &quot; + pass.toString());\n    }\n}\n</code></pre>\n<p>This just adds the password into the string and... yeah, it works well. Check it out... It is very simple; I wrote it.</p>\n'}, {'answer_id': 10189194, 'author': 'user unknown', 'author_id': 312172, 'author_profile': 'https://Stackoverflow.com/users/312172', 'pm_score': 5, 'selected': False, 'text': "<p>A short and easy solution, but it uses only lowercase and numerics:</p>\n<pre><code>Random r = new java.util.Random ();\nString s = Long.toString (r.nextLong () &amp; Long.MAX_VALUE, 36);\n</code></pre>\n<p>The size is about 12 digits to base 36 and can't be improved further, that way. Of course you can append multiple instances.</p>\n"}, {'answer_id': 10361524, 'author': 'Bhavik Ambani', 'author_id': 1145285, 'author_profile': 'https://Stackoverflow.com/users/1145285', 'pm_score': 1, 'selected': False, 'text': '<p>Best Random String Generator Method</p>\n\n<pre><code>public class RandomStringGenerator{\n\n    private static int randomStringLength = 25 ;\n    private static boolean allowSpecialCharacters = true ;\n    private static String specialCharacters = "!@$%*-_+:";\n    private static boolean allowDuplicates = false ;\n\n    private static boolean isAlphanum = false;\n    private static boolean isNumeric = false;\n    private static boolean isAlpha = false;\n    private static final String alphabet = "abcdefghijklmnopqrstuvwxyz";\n    private static boolean mixCase = false;\n    private static final String capAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";\n    private static final String num = "0123456789";\n\n    public static String getRandomString() {\n        String returnVal = "";\n        int specialCharactersCount = 0;\n        int maxspecialCharacters = randomStringLength/4;\n\n        try {\n            StringBuffer values = buildList();\n            for (int inx = 0; inx &lt; randomStringLength; inx++) {\n                int selChar = (int) (Math.random() * (values.length() - 1));\n                if (allowSpecialCharacters)\n                {\n                    if (specialCharacters.indexOf("" + values.charAt(selChar)) &gt; -1)\n                    {\n                        specialCharactersCount ++;\n                        if (specialCharactersCount &gt; maxspecialCharacters)\n                        {\n                            while (specialCharacters.indexOf("" + values.charAt(selChar)) != -1)\n                            {\n                                selChar = (int) (Math.random() * (values.length() - 1));\n                            }\n                        }\n                    }\n                }\n                returnVal += values.charAt(selChar);\n                if (!allowDuplicates) {\n                    values.deleteCharAt(selChar);\n                }\n            }\n        } catch (Exception e) {\n            returnVal = "Error While Processing Values";\n        }\n        return returnVal;\n    }\n\n    private static StringBuffer buildList() {\n        StringBuffer list = new StringBuffer(0);\n        if (isNumeric || isAlphanum) {\n            list.append(num);\n        }\n        if (isAlpha || isAlphanum) {\n            list.append(alphabet);\n            if (mixCase) {\n                list.append(capAlpha);\n            }\n        }\n        if (allowSpecialCharacters)\n        {\n            list.append(specialCharacters);\n        }\n        int currLen = list.length();\n        String returnVal = "";\n        for (int inx = 0; inx &lt; currLen; inx++) {\n            int selChar = (int) (Math.random() * (list.length() - 1));\n            returnVal += list.charAt(selChar);\n            list.deleteCharAt(selChar);\n        }\n        list = new StringBuffer(returnVal);\n        return list;\n    }   \n\n}\n</code></pre>\n'}, {'answer_id': 11577455, 'author': 'Manish Singh', 'author_id': 518493, 'author_profile': 'https://Stackoverflow.com/users/518493', 'pm_score': 7, 'selected': False, 'text': '<p>You can use an <a href="https://en.wikipedia.org/wiki/Apache_Commons" rel="noreferrer">Apache Commons</a> library for this, <a href="http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/RandomStringUtils.html" rel="noreferrer">RandomStringUtils</a>:</p>\n<pre><code>RandomStringUtils.randomAlphanumeric(20).toUpperCase();\n</code></pre>\n'}, {'answer_id': 11629612, 'author': 'Ugo Matrangolo', 'author_id': 1548481, 'author_profile': 'https://Stackoverflow.com/users/1548481', 'pm_score': 2, 'selected': False, 'text': '<p>Here it is a Scala solution:</p>\n\n<pre><code>(for (i &lt;- 0 until rnd.nextInt(64)) yield { \n  (\'0\' + rnd.nextInt(64)).asInstanceOf[Char] \n}) mkString("")\n</code></pre>\n'}, {'answer_id': 12792917, 'author': 'rina', 'author_id': 1730605, 'author_profile': 'https://Stackoverflow.com/users/1730605', 'pm_score': 4, 'selected': False, 'text': '<pre><code>public static String generateSessionKey(int length){\n    String alphabet =\n        new String(&quot;0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz&quot;); // 9\n\n    int n = alphabet.length(); // 10\n\n    String result = new String();\n    Random r = new Random(); // 11\n\n    for (int i=0; i&lt;length; i++) // 12\n        result = result + alphabet.charAt(r.nextInt(n)); //13\n\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 12891357, 'author': 'hridayesh', 'author_id': 1169187, 'author_profile': 'https://Stackoverflow.com/users/1169187', 'pm_score': 2, 'selected': False, 'text': '<p>Using an <a href="https://en.wikipedia.org/wiki/Apache_Commons" rel="nofollow noreferrer">Apache Commons</a> library, it can be done in one line:</p>\n<pre><code>import org.apache.commons.lang.RandomStringUtils;\nRandomStringUtils.randomAlphanumeric(64);\n</code></pre>\n<p><a href="http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/RandomStringUtils.html" rel="nofollow noreferrer">Documentation</a></p>\n'}, {'answer_id': 13072330, 'author': 'Michael Allen', 'author_id': 308474, 'author_profile': 'https://Stackoverflow.com/users/308474', 'pm_score': 5, 'selected': False, 'text': '<p>Surprising, no one here has suggested it, but:</p>\n<pre><code>import java.util.UUID\n\nUUID.randomUUID().toString();\n</code></pre>\n<p>Easy.</p>\n<p>The benefit of this is UUIDs are nice, long, and guaranteed to be almost impossible to collide.</p>\n<p>Wikipedia has <a href="http://en.wikipedia.org/wiki/Universally_unique_identifier#Random_UUID_probability_of_duplicates" rel="nofollow noreferrer">a good explanation</a> of it:</p>\n<blockquote>\n<p>&quot; ...only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.&quot;</p>\n</blockquote>\n<p>The first four bits are the version type and two for the variant, so you get 122 bits of random. So if you <em>want</em> to, you can truncate from the end to reduce the size of the UUID. It\'s not recommended, but you still have loads of randomness, enough for your 500k records easy.</p>\n'}, {'answer_id': 13171599, 'author': 'Prasobh.Kollattu', 'author_id': 1037363, 'author_profile': 'https://Stackoverflow.com/users/1037363', 'pm_score': 2, 'selected': False, 'text': '<p>You can use the following code, if your password mandatory contains numbers and alphabetic special characters:</p>\n<pre><code>private static final String NUMBERS = &quot;0123456789&quot;;\nprivate static final String UPPER_ALPHABETS = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ&quot;;\nprivate static final String LOWER_ALPHABETS = &quot;abcdefghijklmnopqrstuvwxyz&quot;;\nprivate static final String SPECIALCHARACTERS = &quot;@#$%&amp;*&quot;;\nprivate static final int MINLENGTHOFPASSWORD = 8;\n\npublic static String getRandomPassword() {\n    StringBuilder password = new StringBuilder();\n    int j = 0;\n    for (int i = 0; i &lt; MINLENGTHOFPASSWORD; i++) {\n        password.append(getRandomPasswordCharacters(j));\n        j++;\n        if (j == 3) {\n            j = 0;\n        }\n    }\n    return password.toString();\n}\n\nprivate static String getRandomPasswordCharacters(int pos) {\n    Random randomNum = new Random();\n    StringBuilder randomChar = new StringBuilder();\n    switch (pos) {\n        case 0:\n            randomChar.append(NUMBERS.charAt(randomNum.nextInt(NUMBERS.length() - 1)));\n            break;\n        case 1:\n            randomChar.append(UPPER_ALPHABETS.charAt(randomNum.nextInt(UPPER_ALPHABETS.length() - 1)));\n            break;\n        case 2:\n            randomChar.append(SPECIALCHARACTERS.charAt(randomNum.nextInt(SPECIALCHARACTERS.length() - 1)));\n            break;\n        case 3:\n            randomChar.append(LOWER_ALPHABETS.charAt(randomNum.nextInt(LOWER_ALPHABETS.length() - 1)));\n            break;\n    }\n    return randomChar.toString();\n}\n</code></pre>\n'}, {'answer_id': 13678355, 'author': 'Vin', 'author_id': 1621446, 'author_profile': 'https://Stackoverflow.com/users/1621446', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public static String getRandomString(int length)\n{\n    String randomStr = UUID.randomUUID().toString();\n    while(randomStr.length() &lt; length) {\n        randomStr += UUID.randomUUID().toString();\n    }\n    return randomStr.substring(0, length);\n}\n</code></pre>\n'}, {'answer_id': 13686133, 'author': 'Jamie', 'author_id': 1385083, 'author_profile': 'https://Stackoverflow.com/users/1385083', 'pm_score': 1, 'selected': False, 'text': "<p>There are lots of use of StringBuilder in previous answers. I guess it's easy, but it requires a function call per character, growing an array, etc...</p>\n<p>If using the stringbuilder, a suggestion is to specify the required capacity of the string, i.e.,</p>\n<pre><code>new StringBuilder(int capacity);\n</code></pre>\n<p>Here's a version that doesn't use a StringBuilder or String appending, and no dictionary.</p>\n<pre><code>public static String randomString(int length)\n{\n    SecureRandom random = new SecureRandom();\n    char[] chars = new char[length];\n    for(int i=0; i&lt;chars.length; i++)\n    {\n        int v = random.nextInt(10 + 26 + 26);\n        char c;\n        if (v &lt; 10)\n        {\n            c = (char)('0' + v);\n        }\n        else if (v &lt; 36)\n        {\n            c = (char)('a' - 10 + v);\n        }\n        else\n        {\n            c = (char)('A' - 36 + v);\n        }\n        chars[i] = c;\n    }\n    return new String(chars);\n}\n</code></pre>\n"}, {'answer_id': 14021567, 'author': 'duggu', 'author_id': 1722818, 'author_profile': 'https://Stackoverflow.com/users/1722818', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public static String randomSeriesForThreeCharacter() {\n    Random r = new Random();\n    String value = &quot;&quot;;\n    char random_Char ;\n    for(int i=0; i&lt;10; i++)\n    {\n        random_Char = (char) (48 + r.nextInt(74));\n        value = value + random_char;\n    }\n    return value;\n}\n</code></pre>\n'}, {'answer_id': 14241303, 'author': 'Burak T', 'author_id': 1962854, 'author_profile': 'https://Stackoverflow.com/users/1962854', 'pm_score': 1, 'selected': False, 'text': "<p>You can create a character array which includes all the letters and numbers, and then you can randomly select from this character array and create your own string password.</p>\n<pre><code>char[] chars = new char[62]; // Sum of letters and numbers\n\nint i = 0;\n\nfor(char c = 'a'; c &lt;= 'z'; c++) { // For letters\n    chars[i++] = c;\n}\n\nfor(char c = '0'; c &lt;= '9';c++) { // For numbers\n    chars[i++] = c;\n}\n\nfor(char c = 'A'; c &lt;= 'Z';c++) { // For capital letters\n    chars[i++] = c;\n}\n\nint numberOfCodes = 0;\nString code = &quot;&quot;;\nwhile (numberOfCodes &lt; 1) { // Enter how much you want to generate at one time\n    int numChars = 8; // Enter how many digits you want in your password\n\n    for(i = 0; i &lt; numChars; i++) {\n        char c = chars[(int)(Math.random() * chars.length)];\n        code = code + c;\n    }\n    System.out.println(&quot;Code is:&quot; + code);\n}\n</code></pre>\n"}, {'answer_id': 17926222, 'author': 'neuhaus', 'author_id': 2630572, 'author_profile': 'https://Stackoverflow.com/users/2630572', 'pm_score': 2, 'selected': False, 'text': "<p>You can use the UUID class with its getLeastSignificantBits() message to get 64 bit of <em>random</em> data, and then convert it to a radix 36 number (i.e. a string consisting of 0-9,A-Z):</p>\n<pre><code>Long.toString(Math.abs( UUID.randomUUID().getLeastSignificantBits(), 36));\n</code></pre>\n<p>This yields a <em>string</em> up to 13 characters long. We use Math.abs() to make sure there isn't a minus sign sneaking in.</p>\n"}, {'answer_id': 21604071, 'author': 'deepakmodak', 'author_id': 1424605, 'author_profile': 'https://Stackoverflow.com/users/1424605', 'pm_score': 3, 'selected': False, 'text': '<ol>\n<li><p>Change <em>String</em> characters as per as your requirements.</p>\n</li>\n<li><p>String is immutable. Here <code>StringBuilder.append</code> is more efficient than string concatenation.</p>\n</li>\n</ol>\n<br/>\n<pre><code>public static String getRandomString(int length) {\n    final String characters = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&amp;*()_+&quot;;\n    StringBuilder result = new StringBuilder();\n\n    while(length &gt; 0) {\n        Random rand = new Random();\n        result.append(characters.charAt(rand.nextInt(characters.length())));\n        length--;\n    }\n    return result.toString();\n}\n</code></pre>\n'}, {'answer_id': 27120868, 'author': 'Howard Lovatt', 'author_id': 1481689, 'author_profile': 'https://Stackoverflow.com/users/1481689', 'pm_score': 4, 'selected': False, 'text': "<p>An alternative in Java 8 is:</p>\n\n<pre><code>static final Random random = new Random(); // Or SecureRandom\nstatic final int startChar = (int) '!';\nstatic final int endChar = (int) '~';\n\nstatic String randomString(final int maxLength) {\n  final int length = random.nextInt(maxLength + 1);\n  return random.ints(length, startChar, endChar + 1)\n        .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)\n        .toString();\n}\n</code></pre>\n"}, {'answer_id': 27350150, 'author': 'Steven L', 'author_id': 681122, 'author_profile': 'https://Stackoverflow.com/users/681122', 'pm_score': -1, 'selected': False, 'text': '<p>Yet another solution...</p>\n<pre><code>public static String generatePassword(int passwordLength) {\n    int asciiFirst = 33;\n    int asciiLast = 126;\n    Integer[] exceptions = { 34, 39, 96 };\n\n    List&lt;Integer&gt; exceptionsList = Arrays.asList(exceptions);\n    SecureRandom random = new SecureRandom();\n    StringBuilder builder = new StringBuilder();\n    for (int i=0; i&lt;passwordLength; i++) {\n        int charIndex;\n\n        do {\n            charIndex = random.nextInt(asciiLast - asciiFirst + 1) + asciiFirst;\n        }\n        while (exceptionsList.contains(charIndex));\n\n        builder.append((char) charIndex);\n    }\n    return builder.toString();\n}\n</code></pre>\n'}, {'answer_id': 31214709, 'author': 'Kristian Kraljic', 'author_id': 1338417, 'author_profile': 'https://Stackoverflow.com/users/1338417', 'pm_score': 4, 'selected': False, 'text': '<p>Using UUIDs is insecure, because parts of the UUID aren\'t random at all. The <a href="https://stackoverflow.com/questions/41107/how-to-generate-a-random-alpha-numeric-string/41156#41156">procedure of erickson</a> is very neat, but it does not create strings of the same length. The following snippet should be sufficient:</p>\n<pre><code>/*\n * The random generator used by this class to create random keys.\n * In a holder class to defer initialization until needed.\n */\nprivate static class RandomHolder {\n    static final Random random = new SecureRandom();\n    public static String randomKey(int length) {\n        return String.format(&quot;%&quot;+length+&quot;s&quot;, new BigInteger(length*5/*base 32,2^5*/, random)\n            .toString(32)).replace(\'\\u0020\', \'0\');\n    }\n}\n</code></pre>\n<p>Why choose <code>length*5</code>? Let\'s assume the simple case of a random string of length 1, so one random character. To get a random character containing all digits 0-9 and characters a-z, we would need a random number between 0 and 35 to get one of each character.</p>\n<p><code>BigInteger</code> provides a constructor to generate a random number, uniformly distributed over the range <code>0 to (2^numBits - 1)</code>. Unfortunately 35 is not a number which can be received by 2^numBits - 1.</p>\n<p>So we have two options: Either go with <code>2^5-1=31</code> or <code>2^6-1=63</code>. If we would choose <code>2^6</code> we would get a lot of &quot;unnecessary&quot; / &quot;longer&quot; numbers. Therefore <code>2^5</code> is the better option, even if we lose four characters (w-z). To now generate a string of a certain length, we can simply use a <code>2^(length*numBits)-1</code> number. The last problem, if we want a string with a certain length, random could generate a small number, so the length is not met, so we have to pad the string to its required length prepending zeros.</p>\n'}, {'answer_id': 38776878, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>Maybe this is helpful</p>\n\n<pre><code>package password.generater;\n\nimport java.util.Random;\n\n/**\n *\n * @author dell\n */\npublic class PasswordGenerater {\n\n    /**\n     * @param args the command line arguments\n     */\n    public static void main(String[] args) {\n        int length= 11;\n        System.out.println(generatePswd(length));\n\n        // TODO code application logic here\n    }\n    static char[] generatePswd(int len){\n        System.out.println("Your Password ");\n        String charsCaps="ABCDEFGHIJKLMNOPQRSTUVWXYZ"; \n        String Chars="abcdefghijklmnopqrstuvwxyz";\n        String nums="0123456789";\n        String symbols="!@#$%^&amp;*()_+-=.,/\';:?&gt;&lt;~*/-+";\n        String passSymbols=charsCaps + Chars + nums +symbols;\n        Random rnd=new Random();\n        char[] password=new char[len];\n\n        for(int i=0; i&lt;len;i++){\n            password[i]=passSymbols.charAt(rnd.nextInt(passSymbols.length()));\n        }\n      return password;\n\n    }\n}\n</code></pre>\n'}, {'answer_id': 40852832, 'author': 'user_3380739', 'author_id': 3380739, 'author_profile': 'https://Stackoverflow.com/users/3380739', 'pm_score': 3, 'selected': False, 'text': '<p>Here is the one-liner by <a href="https://github.com/landawn/AbacusUtil" rel="nofollow noreferrer">AbacusUtil</a>:</p>\n<pre><code>String.valueOf(CharStream.random(\'0\', \'z\').filter(c -&gt; N.isLetterOrDigit(c)).limit(12).toArray())\n</code></pre>\n<p>Random doesn\'t mean it must be unique. To get unique strings, use:</p>\n<pre><code>N.uuid() // E.g.: &quot;e812e749-cf4c-4959-8ee1-57829a69a80f&quot;. length is 36.\nN.guid() // E.g.: &quot;0678ce04e18945559ba82ddeccaabfcd&quot;. length is 32 without \'-\'\n</code></pre>\n'}, {'answer_id': 44227131, 'author': 'Patrick', 'author_id': 774398, 'author_profile': 'https://Stackoverflow.com/users/774398', 'pm_score': 6, 'selected': False, 'text': '<p>This is easily achievable without any external libraries.</p>\n<h1>1. Cryptographic Pseudo Random Data Generation (PRNG)</h1>\n<p>First you need a cryptographic PRNG. Java has <a href="https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html" rel="noreferrer"><code>SecureRandom</code></a> for that and typically uses the best entropy source on the machine (e.g. <code>/dev/random</code>). <a href="https://tersesystems.com/2015/12/17/the-right-way-to-use-securerandom/" rel="noreferrer">Read more here</a>.</p>\n<pre><code>SecureRandom rnd = new SecureRandom();\nbyte[] token = new byte[byteLength];\nrnd.nextBytes(token);\n</code></pre>\n<p><em><strong>Note:</strong></em> <code>SecureRandom</code> is the slowest, but most secure way in Java of generating random bytes. I do however recommend <em>not</em> considering performance here since it usually has no real impact on your application unless you have to generate millions of tokens per second.</p>\n<h1>2. Required Space of Possible Values</h1>\n<p>Next you have to decide &quot;how unique&quot; your token needs to be. The whole and only point of considering entropy is to make sure that the system can resist brute force attacks: the space of possible values must be so large that any attacker could only try a negligible proportion of the values in non-ludicrous time<sup><a href="https://security.stackexchange.com/a/102163/60108">1</a></sup>.</p>\n<p>Unique identifiers such as random <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier" rel="noreferrer"><code>UUID</code></a> have 122 bit of entropy (i.e., 2^122 = 5.3x10^36) - the chance of collision is &quot;*(...) for there to be a one in a billion chance of duplication, 103 trillion version 4 UUIDs must be generated<sup><a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions" rel="noreferrer">2</a></sup>&quot;. <strong>We will choose 128 bits since it fits exactly into 16 bytes</strong> and is seen as <a href="https://security.stackexchange.com/questions/6141/amount-of-simple-operations-that-is-safely-out-of-reach-for-all-humanity/6149#6149">highly sufficient</a> for being unique for basically every, but the most extreme, use cases and you don\'t have to think about duplicates. Here is a simple comparison table of entropy including simple analysis of the <a href="https://en.wikipedia.org/wiki/Birthday_problem" rel="noreferrer">birthday problem</a>.</p>\n<p><a href="https://i.stack.imgur.com/LoLpJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LoLpJ.png" alt="Comparison of token sizes" /></a></p>\n<p><sup>For simple requirements, 8 or 12 byte length might suffice, but with 16 bytes you are on the &quot;safe side&quot;.</sup></p>\n<p>And that\'s basically it. The last thing is to think about encoding so it can be represented as a printable text (read, a <code>String</code>).</p>\n<h1>3. Binary to Text Encoding</h1>\n<p>Typical encodings include:</p>\n<ul>\n<li><p><a href="https://en.wikipedia.org/wiki/Base64" rel="noreferrer"><code>Base64</code></a> every character encodes 6 bit, creating a 33% overhead. Fortunately there are standard implementations in <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Base64.html" rel="noreferrer">Java 8+</a> and <a href="https://developer.android.com/reference/android/util/Base64.html" rel="noreferrer">Android</a>. With older Java you can use any of the <a href="https://stackoverflow.com/questions/13109588/base64-encoding-in-java">numerous third-party libraries</a>. If you want your tokens to be URL safe use the <a href="https://en.wikipedia.org/wiki/Base64#URL_applications" rel="noreferrer">URL-safe</a> version of RFC4648 (which usually is supported by most implementations). Example encoding 16 bytes with padding: <code>XfJhfv3C0P6ag7y9VQxSbw==</code></p>\n</li>\n<li><p><a href="https://en.wikipedia.org/wiki/Base32" rel="noreferrer"><code>Base32</code></a> every character encodes 5 bit, creating a 40% overhead. This will use <code>A-Z</code> and <code>2-7</code>, making it reasonably space efficient while being case-insensitive alpha-numeric. There isn\'t any <a href="https://stackoverflow.com/questions/21515479/encode-string-to-base32-string-in-java">standard implementation in the JDK</a>. Example encoding 16 bytes without padding: <code>WUPIL5DQTZGMF4D3NX5L7LNFOY</code></p>\n</li>\n<li><p><a href="https://en.wikipedia.org/wiki/Hexadecimal" rel="noreferrer"><code>Base16</code></a> (hexadecimal) every character encodes four bit, requiring two characters per byte (i.e., 16 bytes create a string of length 32). Therefore hexadecimal is less space efficient than <code>Base32</code>, but it is safe to use in most cases (URL) since it only uses <code>0-9</code> and <code>A</code> to <code>F</code>. Example encoding 16 bytes: <code>4fa3dd0f57cb3bf331441ed285b27735</code>. <a href="https://stackoverflow.com/a/58118078/774398">See a Stack\xa0Overflow discussion about converting to hexadecimal here</a>.</p>\n</li>\n</ul>\n<p>Additional encodings like <a href="https://en.wikipedia.org/wiki/Ascii85#RFC_1924_version" rel="noreferrer">Base85</a> and the exotic <a href="http://blog.kevinalbs.com/base122" rel="noreferrer">Base122</a> exist with better/worse space efficiency. You can create your own encoding (which basically most answers in this thread do), but I would advise against it, if you don\'t have very specific requirements. See <a href="https://en.wikipedia.org/wiki/Binary-to-text_encoding" rel="noreferrer">more encoding schemes in the Wikipedia article</a>.</p>\n<h1>4. Summary and Example</h1>\n<ul>\n<li>Use <a href="https://docs.oracle.com/javase/8/docs/api/java/security/SecureRandom.html" rel="noreferrer"><code>SecureRandom</code></a></li>\n<li>Use at least 16 bytes (2^128) of possible values</li>\n<li>Encode according to your requirements (usually <code>hex</code> or <code>base32</code> if you need it to be alpha-numeric)</li>\n</ul>\n<p><strong>Don\'t</strong></p>\n<ul>\n<li>... use your home brew encoding: <em>better maintainable and readable for others if they see what standard encoding you use instead of weird <em>for</em> loops creating characters at a time.</em></li>\n<li>... use UUID: <em>it has no guarantees on randomness; you are wasting 6 bits of entropy and have a verbose string representation</em></li>\n</ul>\n<h2>Example: Hexadecimal Token Generator</h2>\n<pre><code>public static String generateRandomHexToken(int byteLength) {\n    SecureRandom secureRandom = new SecureRandom();\n    byte[] token = new byte[byteLength];\n    secureRandom.nextBytes(token);\n    return new BigInteger(1, token).toString(16); // Hexadecimal encoding\n}\n\n//generateRandomHexToken(16) -&gt; 2189df7475e96aa3982dbeab266497cd\n</code></pre>\n<h2>Example: Base64 Token Generator (URL Safe)</h2>\n<pre><code>public static String generateRandomBase64Token(int byteLength) {\n    SecureRandom secureRandom = new SecureRandom();\n    byte[] token = new byte[byteLength];\n    secureRandom.nextBytes(token);\n    return Base64.getUrlEncoder().withoutPadding().encodeToString(token); //base64 encoding\n}\n\n//generateRandomBase64Token(16) -&gt; EEcCCAYuUcQk7IuzdaPzrg\n</code></pre>\n<h2>Example: Java CLI Tool</h2>\n<p>If you want a ready-to-use CLI tool you may use <a href="https://github.com/patrickfav/dice" rel="noreferrer">dice</a>:</p>\n<h2>Example: Related issue - Protect Your Current Ids</h2>\n<p>If you already have an id you can use (e.g., a synthetic <code>long</code> in your entity), but <a href="https://medium.com/@patrickfav/a-better-way-to-protect-your-database-ids-a33fa9867552" rel="noreferrer">don\'t want to publish the internal value</a>, you can use this library to encrypt it and obfuscate it: <a href="https://github.com/patrickfav/id-mask" rel="noreferrer">https://github.com/patrickfav/id-mask</a></p>\n<pre><code>IdMask&lt;Long&gt; idMask = IdMasks.forLongIds(Config.builder(key).build());\nString maskedId = idMask.mask(id);\n// Example: NPSBolhMyabUBdTyanrbqT8\nlong originalId = idMask.unmask(maskedId);\n</code></pre>\n'}, {'answer_id': 44866347, 'author': 'kyxap', 'author_id': 975638, 'author_profile': 'https://Stackoverflow.com/users/975638', 'pm_score': -1, 'selected': False, 'text': '<p>Also, you can generate any lowercase or uppercase letters or even special characters through data from the ASCII table. For example, generate upper case letters from A (DEC 65) to Z (DEC 90):</p>\n<pre><code>String generateRandomStr(int min, int max, int size) {\n    String result = &quot;&quot;;\n    for (int i = 0; i &lt; size; i++) {\n        result += String.valueOf((char)(new Random().nextInt((max - min) + 1) + min));\n    }\n    return result;\n}\n</code></pre>\n<p>Generated output for <code>generateRandomStr(65, 90, 100));</code>:</p>\n<pre><code>TVLPFQJCYFXQDCQSLKUKKILKKHAUFYEXLUQFHDWNMRBIRRRWNXNNZQTINZPCTKLHGHVYWRKEOYNSOFPZBGEECFMCOKWHLHCEWLDZ\n</code></pre>\n'}, {'answer_id': 48909646, 'author': 'Patrik Bego', 'author_id': 2306839, 'author_profile': 'https://Stackoverflow.com/users/2306839', 'pm_score': 3, 'selected': False, 'text': '<p>I don\'t really like any of these answers regarding a &quot;simple&quot; solution :S</p>\n<p>I would go for a simple ;), pure Java, one liner (entropy is based on random string length and the given character set):</p>\n<pre><code>public String randomString(int length, String characterSet) {\n    return IntStream.range(0, length).map(i -&gt; new SecureRandom().nextInt(characterSet.length())).mapToObj(randomInt -&gt; characterSet.substring(randomInt, randomInt + 1)).collect(Collectors.joining());\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n    for (int q = 0; q &lt; 5; q++) {\n        System.out.println(randomString(10, &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;)); // The character set can basically be anything\n    }\n}\n</code></pre>\n<p>Or (a bit more readable old way)</p>\n<pre><code>public String randomString(int length, String characterSet) {\n    StringBuilder sb = new StringBuilder(); // Consider using StringBuffer if needed\n    for (int i = 0; i &lt; length; i++) {\n        int randomInt = new SecureRandom().nextInt(characterSet.length());\n        sb.append(characterSet.substring(randomInt, randomInt + 1));\n    }\n    return sb.toString();\n}\n\n@Test\npublic void buildFiveRandomStrings() {\n    for (int q = 0; q &lt; 5; q++) {\n        System.out.println(randomString(10, &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789&quot;)); // The character set can basically be anything\n    }\n}\n</code></pre>\n<p>But on the other hand you could also go with <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier#Collisions" rel="nofollow noreferrer">UUID</a> which has a pretty good entropy:</p>\n<pre><code>UUID.randomUUID().toString().replace(&quot;-&quot;, &quot;&quot;)\n</code></pre>\n'}, {'answer_id': 49056893, 'author': 'aaronvargas', 'author_id': 114549, 'author_profile': 'https://Stackoverflow.com/users/114549', 'pm_score': 0, 'selected': False, 'text': "<p>Here's a simple one-liner using UUIDs as the character base and being able to specify (almost) any length. (Yes, I know that using a UUID has been suggested before.)</p>\n<pre><code>public static String randString(int length) {\n    return UUID.randomUUID().toString().replace(&quot;-&quot;, &quot;&quot;).substring(0, Math.min(length, 32)) + (length &gt; 32 ? randString(length - 32) : &quot;&quot;);\n}\n</code></pre>\n"}, {'answer_id': 51896107, 'author': 'Prasad Parab', 'author_id': 6359611, 'author_profile': 'https://Stackoverflow.com/users/6359611', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public static String getRandomString(int length) {\n    char[] chars = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST&quot;.toCharArray();\n\n    StringBuilder sb = new StringBuilder();\n    Random random = new Random();\n    for (int i = 0; i &lt; length; i++) {\n        char c = chars[random.nextInt(chars.length)];\n        sb.append(c);\n    }\n    String randomStr = sb.toString();\n\n    return randomStr;\n}\n</code></pre>\n'}, {'answer_id': 53487039, 'author': 'FileInputStream', 'author_id': 9139738, 'author_profile': 'https://Stackoverflow.com/users/9139738', 'pm_score': 2, 'selected': False, 'text': '<p>I think this is the smallest solution here, or nearly one of the smallest:</p>\n<pre><code> public String generateRandomString(int length) {\n    String randomString = &quot;&quot;;\n\n    final char[] chars = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890&quot;.toCharArray();\n    final Random random = new Random();\n    for (int i = 0; i &lt; length; i++) {\n        randomString = randomString + chars[random.nextInt(chars.length)];\n    }\n\n    return randomString;\n}\n</code></pre>\n<p>The code works just fine. If you are using this method, I recommend you to use more than 10 characters. A collision happens at 5 characters / 30362 iterations. This took 9 seconds.</p>\n'}, {'answer_id': 54907024, 'author': 'mike', 'author_id': 1809463, 'author_profile': 'https://Stackoverflow.com/users/1809463', 'pm_score': 0, 'selected': False, 'text': '<p>Here is a Java 8 solution based on streams.</p>\n\n<pre><code>    public String generateString(String alphabet, int length) {\n        return generateString(alphabet, length, new SecureRandom()::nextInt);\n    }\n\n    // nextInt = bound -&gt; n in [0, bound)\n    public String generateString(String source, int length, IntFunction&lt;Integer&gt; nextInt) {\n        StringBuilder sb = new StringBuilder();\n        IntStream.generate(source::length)\n                .boxed()\n                .limit(length)\n                .map(nextInt::apply)\n                .map(source::charAt)\n                .forEach(sb::append);\n\n        return sb.toString();\n    }\n</code></pre>\n\n<p>Use it like </p>\n\n<pre><code>String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";\nint length = 12;\nString generated = generateString(alphabet, length);\nSystem.out.println(generated);\n</code></pre>\n\n<p>The function <code>nextInt</code> should accept an int <code>bound</code> and return a random number between <code>0</code> and <code>bound - 1</code>.</p>\n'}, {'answer_id': 55376955, 'author': 'SoBeRich', 'author_id': 8305572, 'author_profile': 'https://Stackoverflow.com/users/8305572', 'pm_score': -1, 'selected': False, 'text': "<p>Efficient and short.</p>\n<pre><code>/**\n * Utility class for generating random Strings.\n */\npublic interface RandomUtil {\n\n    int    DEF_COUNT = 20;\n    Random RANDOM    = new SecureRandom();\n\n    /**\n     * Generate a password.\n     *\n     * @return the generated password\n     */\n    static String generatePassword() {\n        return generate(true, true);\n    }\n\n    /**\n     * Generate an activation key.\n     *\n     * @return the generated activation key\n     */\n    static String generateActivationKey() {\n        return generate(false, true);\n    }\n\n    /**\n     * Generate a reset key.\n     *\n     * @return the generated reset key\n     */\n    static String generateResetKey() {\n        return generate(false, true);\n    }\n\n    static String generate(boolean letters, boolean numbers) {\n        int\n            start = ' ',\n            end   = 'z' + 1,\n            count = DEF_COUNT,\n            gap   = end - start;\n        StringBuilder builder = new StringBuilder(count);\n\n        while (count-- != 0) {\n            int codePoint = RANDOM.nextInt(gap) + start;\n\n            switch (getType(codePoint)) {\n                case UNASSIGNED:\n                case PRIVATE_USE:\n                case SURROGATE:\n                    count++;\n                    continue;\n            }\n\n            int numberOfChars = charCount(codePoint);\n\n            if (count == 0 &amp;&amp; numberOfChars &gt; 1) {\n                count++;\n                continue;\n            }\n\n            if (letters &amp;&amp; isLetter(codePoint)\n                || numbers &amp;&amp; isDigit(codePoint)\n                || !letters &amp;&amp; !numbers) {\n\n                builder.appendCodePoint(codePoint);\n                if (numberOfChars == 2)\n                    count--;\n            }\n            else\n                count++;\n        }\n        return builder.toString();\n    }\n}\n</code></pre>\n"}, {'answer_id': 59223550, 'author': 'Riley Jones', 'author_id': 12491840, 'author_profile': 'https://Stackoverflow.com/users/12491840', 'pm_score': 0, 'selected': False, 'text': '<pre><code>public static String RandomAlphanum(int length)\n{\n    String charstring = &quot;abcdefghijklmnopqrstuvwxyz0123456789&quot;;\n    String randalphanum = &quot;&quot;;\n    double randroll;\n    String randchar;\n    for (double i = 0; i &lt; length; i++)\n    {\n        randroll = Math.random();\n        randchar = &quot;&quot;;\n        for (int j = 1; j &lt;= 35; j++)\n        {\n            if (randroll &lt;= (1.0 / 36.0 * j))\n            {\n                randchar = Character.toString(charstring.charAt(j - 1));\n                break;\n            }\n        }\n        randalphanum += randchar;\n    }\n    return randalphanum;\n}\n</code></pre>\n<p>I used a very primitive algorithm using Math.random(). To increase randomness, you can directly implement the <code>util.Date</code> class. Nevertheless, it works.</p>\n'}, {'answer_id': 61152198, 'author': 'Chuong Tran', 'author_id': 8568835, 'author_profile': 'https://Stackoverflow.com/users/8568835', 'pm_score': 3, 'selected': False, 'text': '<p>I\'m using a library from <a href="https://en.wikipedia.org/wiki/Apache_Commons" rel="nofollow noreferrer">Apache Commons</a> to generate an alphanumeric string:</p>\n<pre><code>import org.apache.commons.lang3.RandomStringUtils;\n\nString keyLength = 20;\nRandomStringUtils.randomAlphanumeric(keylength);\n</code></pre>\n<p>It\'s fast and simple!</p>\n'}, {'answer_id': 67010786, 'author': 'Mayank', 'author_id': 9297984, 'author_profile': 'https://Stackoverflow.com/users/9297984', 'pm_score': -1, 'selected': False, 'text': "<p>I am using a very simple solution using Java 8. Just customize it according to your needs.</p>\n<pre><code>...\nimport java.security.SecureRandom;\n...\n\n//Generate a random String of length between 10 to 20.\n//Length is also randomly generated here.\nSecureRandom random = new SecureRandom();\n\nString sampleSet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_&quot;;\n\nint stringLength = random.ints(1, 10, 21).mapToObj(x -&gt; x).reduce((a, b) -&gt; a).get();\n\nString randomString = random.ints(stringLength, 0, sampleSet.length() - 1)\n        .mapToObj(x -&gt; sampleSet.charAt(x))\n        .collect(Collector\n            .of(StringBuilder::new, StringBuilder::append,\n                StringBuilder::append, StringBuilder::toString));\n</code></pre>\n<hr />\n<p>We can use this to generate an alphanumeric random String like this (the returned String will mandatorily have some non-numeric characters as well as some numeric characters):</p>\n<pre><code>public String generateRandomString() {\n            \n    String sampleSet = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_&quot;;\n    String sampleSetNumeric = &quot;0123456789&quot;;\n    \n    String randomString = getRandomString(sampleSet, 10, 21);\n    String randomStringNumeric = getRandomString(sampleSetNumeric, 10, 21);\n    \n    randomString = randomString + randomStringNumeric;\n    \n    //Convert String to List&lt;Character&gt;\n    List&lt;Character&gt; list = randomString.chars()\n            .mapToObj(x -&gt; (char)x)\n            .collect(Collectors.toList());\n    \n    Collections.shuffle(list);\n    \n    //This is needed to force a non-numeric character as the first String\n    //Skip this for() if you don't need this logic\n\n    for(;;) {\n        if(Character.isDigit(list.get(0))) Collections.shuffle(list);\n        else break;\n    }\n    \n    //Convert List&lt;Character&gt; to String\n    randomString = list.stream()\n            .map(String::valueOf)\n            .collect(Collectors.joining());\n    \n    return randomString;\n    \n}\n\n//Generate a random number between the lower bound (inclusive) and upper bound (exclusive)\nprivate int getRandomLength(int min, int max) {\n    SecureRandom random = new SecureRandom();\n    return random.ints(1, min, max).mapToObj(x -&gt; x).reduce((a, b) -&gt; a).get();\n}\n\n//Generate a random String from the given sample string, having a random length between the lower bound (inclusive) and upper bound (exclusive)\nprivate String getRandomString(String sampleSet, int min, int max) {\n    SecureRandom random = new SecureRandom();\n    return random.ints(getRandomLength(min, max), 0, sampleSet.length() - 1)\n    .mapToObj(x -&gt; sampleSet.charAt(x))\n    .collect(Collector\n        .of(StringBuilder::new, StringBuilder::append,\n            StringBuilder::append, StringBuilder::toString));\n}\n</code></pre>\n"}, {'answer_id': 67020131, 'author': 'Muxammed Gafarov', 'author_id': 13589507, 'author_profile': 'https://Stackoverflow.com/users/13589507', 'pm_score': 2, 'selected': False, 'text': '<pre><code>public class Utils {\n    private final Random RANDOM = new SecureRandom();\n    private final String ALPHABET = &quot;0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm&quot;;\n\n    private String generateRandomString(int length) {\n        StringBuffer buffer = new StringBuffer(length);\n        for (int i = 0; i &lt; length; i++) {\n            buffer.append(ALPHABET.charAt(RANDOM.nextInt(ALPHABET.length())));\n        }\n        return new String(buffer);\n    } \n}\n</code></pre>\n'}, {'answer_id': 74024384, 'author': 'cwtuan', 'author_id': 2822680, 'author_profile': 'https://Stackoverflow.com/users/2822680', 'pm_score': 0, 'selected': False, 'text': '<p>Given the some characters (<code>AllCharacters</code>), you could pickup a character in the string randomly. Then use-for loop to get random charcter repeatedly.</p>\n<pre class="lang-java prettyprint-override"><code>public class MyProgram {\n  static String getRandomString(int size) {\n      String AllCharacters = &quot;ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789&quot;;\n      StringBuilder sb = new StringBuilder(size);\n      int length = AllCharacters.length();\n      for (int i = 0; i &lt; size; i++) {\n          sb.append(AllCharacters.charAt((int)(length * Math.random())));\n      }\n      return sb.toString();\n  }\n\n  public static void main(String[] args) {\n      System.out.println(MyProgram.getRandomString(30));\n  }\n}\n</code></pre>\n<ul>\n<li>Try it on the <a href="https://codehs.com/sandbox/id/java-main-4NaSkG" rel="nofollow noreferrer">sandbox</a></li>\n<li>Also see other languages implement <a href="https://fe-tool.com/en-us/random-password" rel="nofollow noreferrer">random string generator</a></li>\n</ul>\n'}, {'answer_id': 74402390, 'author': 'F_SO_K', 'author_id': 4985580, 'author_profile': 'https://Stackoverflow.com/users/4985580', 'pm_score': 0, 'selected': False, 'text': "<p>You can do this in one line with no external libraries.</p>\n<pre><code>int length = 12;\nString randomString = new Random().ints(48, 122).filter(i -&gt; (i &lt; 58 || i &gt; 64) &amp;&amp; (i &lt; 91 || i &gt; 96)).limit(length).collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();\nSystem.out.print(randomString);\n</code></pre>\n<p>I have separated out the length into a parameter, and added a line to print the result.</p>\n<p>This code creates a stream of random integers bounded to the alphanumeric ascii range. It then filters out some symbols, because the alphanumeric range is not continuous. It then limits the length and collects the result into a string.</p>\n<p>Because this approach discards something like 20% of the numbers/characters it generates (as they are symbols), there is a small performance impact.</p>\n<p>I don't find it particularly readable, but I don't think anyone else has suggested a native Java solution in one line.</p>\n"}]
['https://Stackoverflow.com/questions/41107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3803/']