Open In App

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




// 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




// 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


Article Tags :