Java generate random string

Java provides many different ways to generate a random string and this post will explain most of those.

Generation of random sequence of characters is often required

  • to create a unique identifier such as transaction ids in banking applications.
  • as a random password generator which provides a temporary password for user registering for the first time on a website.
  • Random string for creating captcha to prevent automated input etc.
Method 1: Using UUID
java.util.UUID class can be used to get 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 alphanumeric 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'

Method 5: Using java 8 Stream
With Java 8 streams, we can generate a random alphanumeric string of fixed length.
The idea is to generate a stream of random numbers between ASCII values of 0-9, a-z and A-Z, convert each integer generated into corresponding character and append this character to a StringBuffer.

Example code is given below

import java.util.Random;

public class RandomStringGenerator {
  public static void main(String[] args) throws IOException {
    Random r = new Random();
    String s = r.ints(48, 123)
                .filter(num -> (num < 58 || num > 64) && (num < 91 || num > 96))
    .limit(10)
    .mapToObj(c -> (char) c).collect(StringBuffer::new, StringBuffer::append, StringBuffer::append)
          .toString();
    System.out.println('Random alphanumeric string is: " + s);
  }
}

java.util.Random class has a new method ints() added in java 8.

ints() takes two integer arguments and generates a stream of integers between those two integers with start inclusive and end exclusive.
This stream is filtered with filter() method to include ASCII values of only 0-9, a-z and A-Z.
If you want other characters as well, then filter() is not required.

limit() is required to generate a random string of 10 characters. Without limit(), the stream will keep on generating integers infinitely.

mapToObj() converts integer value to corresponding character.
Both filter() and mapToObj() accept a functional interface as argument and so we can pass a Lambda expression.

Finally, collect() is used to collect the values generated by the stream into a StringBuffer using its append() method.
This StringBuffer is converted to a string with toString() method.

Range of integers provided to ints() is chosen according to ASCII values of numbers and alphabets. You can choose these according to the characters that need to be included in the string to generate.

Multiple executions of this program generate following output

Random alphanumeric string is: tCh5OTWY4v
Random alphanumeric string is: pHLjsd0ts4
Random alphanumeric string is: L82EvKMfsm

That is all on different ways to generate a random string in java. Hope the article was helpful !!

0
Liked the article ? Spread the word...