Generate array of random strings in Java

Welcome, in this tutorial we will learn how to generate an array of random strings in Java. We use java.util.Random class for generating the random string and store in java array string object that contains the elements of string data type.

Java program to create array of random strings

public class ArrayRandomStrings {

    //Here we have created a static function that takes arguments string length and array size
    //and returns a Array of String object
    static String[] createAlphaNumericArrayStrings(int stringLength, int sizeOfStringArray) {

        //defining the content of the string.
        String allCharStringContains = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                + "0123456789"
                + "abcdefghijklmnopqrstuvxyz";

        //.length() returns the total number of characters contained in the string
        int maximum = allCharStringContains.length();

        StringBuffer stringBufferObj;
        //here array of a string is created with the size we sent as an argument.
        String[] stringArray = new String[sizeOfStringArray];

        //Creating the Random object;
        Random randomObj = new Random();
  • Line number 5, we create a static createAlphaNumericArrayStrings(int stringLength, int sizeOfStringArray) function which returns a string array object and takes two arguments which are the length of string and the size of the array
  • Line number 8, a string variable named as allCharStringContains it contains the characters (Alphabetic and Numeric) which are used to generate the random string.
  • Line number 13, an int variable that stores the number of characters present in the string with the help of .length() method.
  • Line number 15, we create a stringBufferObj variable, which is of type StringBuffer.
  • Line number 17, an array of strings with size as an argument sizeOfStringArray.
  • Line number 20, an object of the Random class which is from java.util package.

Logical section of code

        //this for loop helps to generate a number of strings which we provided 
        //and stores that srings in array
        for (int i = 0; i < sizeOfStringArray; i++) {

            //creating new StringBuffer object for each string
            stringBufferObj = new StringBuffer();

            //creating a string from allCharStringContains 
            for (int j = 0; j < stringLength; j++) {

                int createdRandomChar = randomObj.nextInt(maximum);

                stringBufferObj.append(allCharStringContains.charAt(createdRandomChar));

            }
            //setting a created string into stringArray in index[i]
            stringArray[i] = stringBufferObj.toString();

        }
        //returning the Array of Strings object
        return stringArray;

    }
  • Line number 3, using this for loop, we can generate how many times a random string will generate and it will store into our stringArray at the specified location [i].
  • Line number 6, using the new keyword, we create a new StringBuffer object and store it in stringBufferObj variable.
  • Line number 9, using this for loop, we generate a string of random characters and the length of the string specified in stringLength.
  • Line number 11, we get the number in the createdRandomChar variable and our code does not exceed the maximum value. it will generate a random number from 0 to maximum using the randomObj.nextInt(maximum) method.
  • Line number 13, using stringbufferObj.append() method we build our random string using allCharStringContains.charAt(createdRandomChar), charAt() method returns the character at the index number createdRandomChar.
  • Line number 17, using stringBufferObj.toString() returns the object as a string and stores in stringArray at index [i].
  • Line number 21, returning the object stringArray.
public static void main(String[] args) {
        //setting the size of string as well as array
        int createStringLength = 25;
        int createArraySize = 5;

        //here we receive the array of strings from our static function 
        String[] generatedStrings = ArrayRandomStrings.createAlphaNumericArrayStrings(createStringLength, createArraySize);

        //printing the array of strings that we generated
        System.out.println("Generated array of Random strings are"
                + "\n"
                + "=============================");
        for (String a : generatedStrings) {
            System.out.println(a);
        }
        System.out.println("=============================");
    }
}

Line number 7, calling the static method createAlphaNumericArrayStrings(createStringLength,createArraySize), which takes the size of string as argument createStringLength, size of the array as argument createArraySize and returns the String object generatedStrings.

Line number 13, using an enhance-for loop to print our random strings from the array.

Output

Generated array of Random strings are
=============================
4bZXMOSB8YmDyvmjUjpAMIXOl
96Ep3i110hqQ2cIUtotp5OGS8
IvqusF8TA31OMSxqEZK3MG7kj
7xkEfICq9pqr8sbmUYRtICP9x
rInOc3BRYfVcNjCCCVx5JRSGg
=============================

Also read: Java Program to Generate Array of Random Integers

Leave a Reply

Your email address will not be published.