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:
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
Recommended Posts:
- Program to generate random alphabets
- Random vs Secure Random numbers in Java
- Generate all rotations of a given string
- Program to generate all possible valid IP addresses from given string
- Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
- Generate lexicographically smallest string of 0, 1 and 2 with adjacent swaps allowed
- Generate two output strings depending upon occurrence of character in input string.
- Generate two output strings depending upon occurrence of character in input string in Python
- Java.util.Random.nextInt() in Java
- Java.util.Random class in Java
- StrictMath random() Method in Java
- Generating random numbers in Java
- A Java Random and StringBuffer Puzzle
- Random next() method in Java with Examples
- Random nextBoolean() method in Java with Examples
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.



