Generate random String of given size in Java
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:
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
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));}}Output: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));}}Output: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));}}Output: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));}}Output:qbhalyuzrenuwgvqidno


