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.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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)
        {
      
            // chose 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));
        }
    }

    chevron_right

    
    

    Output:

    kU9vRVm9T1lFMbi3duO1
    

    Method 2: Using CharSet

    Generate 20 character long alphanumeric string randomly using Charset which is in java.nio.charset package.

    1. First take char between 0 to 256 and traverse.
    2. Check char is alphabetic or numeric.
    3. If yes, then add at the end of our String
    4. Return String

    Below is the implementation of the above approach:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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));
        }
    }

    chevron_right

    
    

    Output:

    jj06CyZKfSBZQHM6KAUd
    
  • Method 3: Using Regular Expressions
    1. First take char between 0 to 256.
    2. remove all char except 0-9, a-z and A-Z.
    3. Random select an char
    4. Add at the end our required variable

    Below is the implementation of the above approach:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program generate a random AlphaNumeric String
    // using Regular Expressions 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();
      
            // remove all spacial char
            String  AlphaNumericString
                = randomString
                      .replaceAll("[^A-Za-z0-9]", "");
      
            // Append first 20 alphanumeric characters
            // from the generated random String into the result
            for (int k = 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 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));
        }
    }

    chevron_right

    
    

    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:

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Java program generate a random
    // UpperCase or LowerCase or Number String
      
    import java.util.*;
      
    public class GFG {
      
        static String getAlphaNumericString(int n)
        {
      
            // lower limit for LowerCase Letters
            int lowerLimit = 97;
      
            // lower limit for LowerCase Letters
            int upperLimit = 122;
      
            Random random = new Random();
      
            // Create a StringBuffer to store the result
            StringBuffer r = new StringBuffer(n);
      
            for (int i = 0; i < n; i++) {
      
                // take a random value between 97 and 122
                int nextRandomChar = lowerLimit
                                     + (int)(random.nextFloat()
                                             * (upperLimit - lowerLimit + 1));
      
                // append a character at the end of bs
                r.append((char)nextRandomChar);
            }
      
            // 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));
        }
    }

    chevron_right

    
    

    Output:

    qbhalyuzrenuwgvqidno
    


My Personal Notes arrow_drop_up

Strategy Path planning and Destination matters in success No need to worry about in between temporary failures

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.