How to generate random string in java / 4 ways to generate random string in java

Generation of random sequence of characters is often required when you want to display a unique transaction id or as a random password generator which provides a temporary password for user registering for the first time on a website or while creating captcha for preventing automated input etc.
Java provides many different ways to program a random string generator application and this post will explain most of those.


Method 1: Using UUID
java.util.UUID class can be used to generate a random string. Its static randomUUID method acts as a random alphanumeric generator and returns a String of 32 characters.
If you want a string of a fixed length or shorter than 32 characters, you can use substring method of java.lang.String.
Example,

import java.util.UUID;
 
public class RandomStringGenerator {
 
   public static void main(String[] args) {
	String randomString = usingUUID();
	System.out.println("Random string is: " + randomString);
	System.out.println("Random string of 8 characters is: "
                 + randomString.substring(0, 8));
   }
 
   static String usingUUID() {
	UUID randomUUID = UUID.randomUUID();
	return randomUUID.toString().replaceAll("-", "");
   }
}

Note that the string generated by randomUUID method contains ““. Above example removes those by replacing them with empty string.
Output of above program will be

Random string is: 923ed6ec4d04452eaf258ec8a4391a0f
Random string of 8 characters is: 923ed6ec


Method 2: Using Math class
Following algorithm can be used to generate a random string of fixed length using this method.

  1. Initialize an empty string to hold the result.
  2. Create a combination of upper and lower case alphabets and numerals to create a super set of characters.
  3. Initiate a loop for with count equal to the length of random string required.
  4. In every iteration, generate a random number between 0 and the length of super set.
  5. Extract the character from the string in Step 2 at the index of number generated in Step 4 and add it to the string in Step 1.
    After the loop completes, string in Step 1 will be a random string.

Java program follows.

import java.util.Math;
 
public class RandomStringGenerator {
 
   public static void main(String[] args) {
	String randomString = usingMath();
	System.out.println("Random string is: " + randomString);
   }
 
 
   static String usingMath() {
	String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz";
	String numbers = "0123456789";
        // create a super set of all characters
	String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers;
        // initialize a string to hold result
	StringBuffer randomString = new StringBuffer();
        // loop for 10 times
	for (int i = 0; i < 10; i++) {
           // generate a random number between 0 and length of all characters 
	   int randomIndex = (int)(Math.random() * allCharacters.length());
           // retrieve character at index and add it to result
	   randomString.append(allCharacters.charAt(randomIndex));
	}
	return randomString.toString();
   }
}

Output of above program executed thrice is

Random string is: kqNG2SYHeF
Random string is: lCppqqUg8P
Random string is: GGiFiEP5Dz

This approach gives you more control over the characters that need to be included in the random string. For example, if you do not want numbers, then remove them from the super set. If you want special characters, then add a set of special characters in the super set.


Method 3: Using Random class
This method follows a similar approach as the above method in that a super set of all the characters is created, a random index is generated and character at that index is used to create the final string.
But this approach uses java.util.Random class to generate a random index. Example,

import java.util.Random;
 
public class RandomStringGenerator {
 
   public static void main(String[] args) {
	String randomString = usingRandom();
	System.out.println("Random string is: " + randomString);
   }
 
 
   static String usingRandom() {
	String alphabetsInUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	String alphabetsInLowerCase = "abcdefghijklmnopqrstuvwxyz";
	String numbers = "0123456789";
        // create a super set of all characters
	String allCharacters = alphabetsInLowerCase + alphabetsInUpperCase + numbers;
        // initialize a string to hold result
	StringBuffer randomString = new StringBuffer();
        // loop for 10 times
	for (int i = 0; i < 10; i++) {
           // generate a random number between 0 and length of all characters 
	   int randomIndex = random.nextInt(allCharacters.length());
           // retrieve character at index and add it to result
	   randomString.append(allCharacters.charAt(randomIndex));
	}
	return randomString.toString();
   }
}

You can also use java.util.SecureRandom class to generate a random integer. It is a subclass of java.util.Random.
Output of three executions of above program is

Random string is: TycOBOxITs
Random string is: 7LLWVbg0ps
Random string is: p6VyqdO6bT



Method 4
: Using RandomStringUtils

Apache Commons Lang library has an org.apache.commons.lang.RandomStringUtils class with methods to generate random string of a fixed length.
It has methods that can generate a random string of only alphabets(randomAlphabetic), numbers(randomNumeric) or both(randomAlphanumeric).
All these methods accept an integer argument which represents the length of the string that they will generate.
Below is an example.

import org.apache.commons.lang.RandomStringUtils;
 
public class RandomStringGenerator {
 
   public static void main(String[] args) {
	// generate a random string of 10 alphabets
	String randomString = RandomStringUtils.randomAlphabetic(10);
	System.out.println("Random string of 10 alphabets: " + randomString);
	randomString = RandomStringUtils.randomNumeric(10);
	System.out.println("Random string of 10 numbers: " + randomString);
	randomString = RandomStringUtils.randomAlphanumeric(10);
	System.out.println("Random string of 10 alphanumeric characters: " + randomString);
   }
}

Output of above program is

Random string of 10 alphabets: OEfadIYfFm
Random string of 10 numbers: 1639479195
Random string of 10 alphanumeric characters: wTQRMXrNY9

This class also has a method random that takes an integer which is the length of the string to be generated and a char array. Random string generated consists of only characters from this array.

Apache Commons Lang can be included into your project by adding the below dependency as per the build tool.

<!–Maven –>
<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-lang3</artifactId>
   <version>3.9</version>
</dependency>

// Gradle
compile group: ‘org.apache.commons’, name: ‘commons-lang3’, version: ‘3.9’

Hope this post was helpful for you. Do you know any other random string generator approach? If yes, then do share it in the comments section below.

0

Mark Your Impression

Close Menu