Given a size as n, The task is to generate a random alphanumeric String of this size.
Below are various ways to generate random alphanumeric String of given size:
Prerequisite : Generating random numbers in Java
- Method 1: Using Math.random()
Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb. In the end sb is returned.
// Java program generate a random AlphaNumeric String// using Math.random() methodpublicclassRandomString {// function to generate a random string of length nstaticString getAlphaNumericString(intn){// chose a Character random from this StringString AlphaNumericString ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"+"0123456789"+"abcdefghijklmnopqrstuvxyz";// create StringBuffer size of AlphaNumericStringStringBuilder sb =newStringBuilder(n);for(inti =0; i < n; i++) {// generate a random number between// 0 to AlphaNumericString variable lengthintindex= (int)(AlphaNumericString.length()* Math.random());// add Character one by one in end of sbsb.append(AlphaNumericString.charAt(index));}returnsb.toString();}publicstaticvoidmain(String[] args){// Get the size nintn =20;// Get and display the alphanumeric stringSystem.out.println(RandomString.getAlphaNumericString(n));}}chevron_rightfilter_noneOutput:
kU9vRVm9T1lFMbi3duO1
Method 2: Using CharSet
Generate 20 character long alphanumeric string randomly using Charset which is in java.nio.charset package.
- First take char between 0 to 256 and traverse.
- Check char is alphabetic or numeric.
- If yes, then add at the end of our String
- Return String
Below is the implementation of the above approach:
// Java program generate a random AlphaNumeric String// using CharSet methodimportjava.util.*;importjava.nio.charset.*;classRandomString {staticString getAlphaNumericString(intn){// length is bounded by 256 Characterbyte[] array =newbyte[256];newRandom().nextBytes(array);String randomString=newString(array, Charset.forName("UTF-8"));// Create a StringBuffer to store the resultStringBuffer r =newStringBuffer();// Append first 20 alphanumeric characters// from the generated random String into the resultfor(intk =0; k < randomString.length(); k++) {charch = randomString.charAt(k);if(((ch >='a'&& ch <='z')|| (ch >='A'&& ch <='Z')|| (ch >='0'&& ch <='9'))&& (n >0)) {r.append(ch);n--;}}// return the resultant stringreturnr.toString();}publicstaticvoidmain(String[] args){// size of random alphanumeric stringintn =20;// Get and display the alphanumeric stringSystem.out.println(getAlphaNumericString(n));}}chevron_rightfilter_noneOutput:jj06CyZKfSBZQHM6KAUd
- Method 3: Using Regular Expressions
- First take char between 0 to 256.
- remove all char except 0-9, a-z and A-Z.
- Random select an char
- Add at the end our required variable
Below is the implementation of the above approach:
// Java program generate a random AlphaNumeric String// using Regular Expressions methodimportjava.util.*;importjava.nio.charset.*;classRandomString {staticString getAlphaNumericString(intn){// length is bounded by 256 Characterbyte[] array =newbyte[256];newRandom().nextBytes(array);String randomString=newString(array, Charset.forName("UTF-8"));// Create a StringBuffer to store the resultStringBuffer r =newStringBuffer();// remove all spacial charString AlphaNumericString= randomString.replaceAll("[^A-Za-z0-9]","");// Append first 20 alphanumeric characters// from the generated random String into the resultfor(intk =0; k < AlphaNumericString.length(); k++) {if(Character.isLetter(AlphaNumericString.charAt(k))&& (n >0)|| Character.isDigit(AlphaNumericString.charAt(k))&& (n >0)) {r.append(AlphaNumericString.charAt(k));n--;}}// return the resultant stringreturnr.toString();}publicstaticvoidmain(String[] args){// size of random alphanumeric stringintn =20;// Get and display the alphanumeric stringSystem.out.println(getAlphaNumericString(n));}}chevron_rightfilter_noneOutput:4J8pirLzX6oIF0IIIaUU
- Method 4: Generating random String of UpperCaseLetter/LowerCaseLetter/Numbers
When some specific characters are needed in the alphanumeric string, like only the UpperCaseLetter or LowerCaseLetter or Numbers, use this method. Below example generates a random String of LowerCase letters of size n.
Below is the implementation of the above approach:
// Java program generate a random// UpperCase or LowerCase or Number Stringimportjava.util.*;publicclassGFG {staticString getAlphaNumericString(intn){// lower limit for LowerCase LettersintlowerLimit =97;// lower limit for LowerCase LettersintupperLimit =122;Random random =newRandom();// Create a StringBuffer to store the resultStringBuffer r =newStringBuffer(n);for(inti =0; i < n; i++) {// take a random value between 97 and 122intnextRandomChar = lowerLimit+ (int)(random.nextFloat()* (upperLimit - lowerLimit +1));// append a character at the end of bsr.append((char)nextRandomChar);}// return the resultant stringreturnr.toString();}publicstaticvoidmain(String[] args){// size of random alphanumeric stringintn =20;// Get and display the alphanumeric stringSystem.out.println(getAlphaNumericString(n));}}chevron_rightfilter_noneOutput:qbhalyuzrenuwgvqidno
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.
Recommended Posts:
- Generate a string of size N whose each substring of size M has exactly K distinct characters
- How to Generate a Random Directed Acyclic Graph for a Given Number of Edges in Java?
- Generate a string whose all K-size substrings can be concatenated to form the given string
- Random vs Secure Random numbers in Java
- How to Create a Random Graph Using Random Edge Generation in Java?
- How do I generate random integers within a specific range in Java?
- Generate Random Numbers Using Middle Square Method in Java
- Java Program to Generate Random Hexadecimal Bytes
- Java Program to Generate Random Numbers Using Multiply with Carry Method
- Program to generate random alphabets
- How to generate a random color for a Matplotlib plot in Python?
- Generate an array of given size with equal count and sum of odd and even numbers
- Generate a String from given Strings P and Q based on the given conditions
- Java.util.Random class in Java
- Java.util.Random.nextInt() in Java
- Different Ways to Generate String by using Characters and Numbers in Java
- Generate all rotations of a given string
- Program to generate all possible valid IP addresses from given string
- Program to generate all possible valid IP addresses from given string | Set 2
- Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

