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
// Java program generate a random AlphaNumeric String // using Math.random() method Â
public class RandomString { Â
 // function to generate a random string of length n  static String getAlphaNumericString(int n)  { Â
  // choose a Character random from this String   String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"         + "0123456789"         + "abcdefghijklmnopqrstuvxyz"; Â
  // create StringBuffer size of AlphaNumericString   StringBuilder sb = new StringBuilder(n); Â
  for (int i = 0; i < n; i++) { Â
   // generate a random number between    // 0 to AlphaNumericString variable length    int index     = (int)(AlphaNumericString.length()       * Math.random()); Â
   // add Character one by one in end of sb    sb.append(AlphaNumericString       .charAt(index));   } Â
  return sb.toString();  } Â
 public static void main(String[] args)  { Â
  // Get the size n   int n = 20; Â
  // Get and display the alphanumeric string   System.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
- 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
- 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
// Java program generate a random AlphaNumeric String // using CharSet method Â
import java.util.*; import java.nio.charset.*; Â
class RandomString { Â
 static String getAlphaNumericString(int n)  { Â
  // length is bounded by 256 Character   byte[] array = new byte[256];   new Random().nextBytes(array); Â
  String randomString    = new String(array, Charset.forName("UTF-8")); Â
  // Create a StringBuffer to store the result   StringBuffer r = new StringBuffer(); Â
  // Append first 20 alphanumeric characters   // from the generated random String into the result   for (int k = 0; k < randomString.length(); k++) { Â
   char ch = 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 string   return r.toString();  } Â
 public static void main(String[] args)  {   // size of random alphanumeric string   int n = 20; Â
  // Get and display the alphanumeric string   System.out.println(getAlphaNumericString(n));  } } |
Output:
qbhalyuzrenuwgvqidno
Time complexity: O(n) where n is size of string to be generated
Auxiliary space: O(n) for StringBuffer
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



