Generate Random String in Java

May 09, 2022
GenerateStrings



Introduction

Generating a random string might seem like a trivial task but it is not as simple as you think. A truly random string is often needed to be generated for some very sensitive tasks such as for creating a unique identifier for bank transactions or for creating captcha for automated input prevention even for creating temporary passwords for users for their very first login.

Such crucial tasks demand a fool-proof non-repeating random strings generator. Java developers are in luck as there are various ways available to generate a random string in Java.

In this article, we will be discussing some easiest approaches using different classes, methods and Java libraries to generate a random string in Java. We will be covering different types of strings ranging from numeric, alpha-numeric, with special characters etc.

new java job roles

Using Math.random()

The math class offer a variety of methods for different numeric operations. One such method is math.Random(). It is used to generate a random number of double data type ranging from 0.0 and 1.0, inclusive.

 

See this example below showing how to use the Math.random() method:

import java.util.*;
public class Main
{
  public static void main(String args[])
  {
  System.out.println(Math.random());
  }
}
Output: 0.8034534245253324

You might be wondering, how come a random double number generating class can be used to generate random string in Java.

A random alphanumeric string of your required length can be easily created by combining this randomly generated number with a few other methods.

 

The following code demonstration shows the generation of an alphanumeric string using Math.Random() function:

public class Main {

 // defining a function to generate a random string of length l

 static String RandGeneratedStr(int l)

 {

 // a list of characters to choose from in form of a string

 String AlphaNumericStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789”;

 // creating a StringBuffer size of AlphaNumericStr

 StringBuilder s = new StringBuilder(l);

 int i;

 for ( i=0; i<l; i++) {

   //generating a random number using math.random()

   int ch = (int)(AlphaNumericString.length() * Math.random());

   //adding Random character one by one at the end of s

   s.append(AlphaNumericStr.charAt(ch));

  }

    return s.toString();

 }

 public static void main(String[] args)

 {

  //assign the size of the string

  int n = 10;

  //Output the randomly generated alphanumeric string

  System.out.println(Main.RandGeneratedStr(n));

 }

}
Output: lq46joFI45y0POU

Here, we have used a set of small case, large case and numeric values to be part of the random string but you can use any characters of your choice including special characters.

You can also create multiple strings containing just numbers, or characters and can concatenate them later, there are endless possibilities to generate a random string in Java using math.random().

Using randomUUID()

java.util.UUID is another Java class that can be used to generate a random string. It offers a static randomUUID() method that returns a random alphanumeric string of 32 characters.

 

See this example below:

import java.util.UUID;

public class RandomStrGenerator {

  public static void main(String[] args) {

    String randomStr = usingRandomUUID();

    System.out.println("A random string of 32 characters: " + randomStr);

    );

  }

  static String usingRandomUUID() {

    UUID randomUUID = UUID.randomUUID();

    return randomUUID.toString().replaceAll("_", "");

  }

}
Output:

A random string of 32 characters: lk324jlk32h5lwuHorewuJH234adsaQf

Now it is to be noted that the randomly generated string also have random occurrences of ‘_’. It can easily be dealt with by using the replaceAll() method at the end to replace all the ’_’ with an empty string.

 

This method can only generate a 32 character string but to generate a string shorter than 32 characters, you can just use the substring() method of java.lang.String as shown in the code below:

import java.util.UUID;

import java.util.Scanner;

public class RandomStrGenerator {

  public static void main(String[] args) {

    String randomStr = usingRandomUUID();

    Scanner input = new Scanner(System.in);     

        System.out.print("Enter the length of random String to be generated: ");

        int len = input.nextInt();


    System.out.println("A random string of ” + len + “ characters : " + randomStr);

    input.close();

 }  

 static String usingRandomUUID() {

    UUID randomUUID = UUID.randomUUID();

    return randomUUID.toString().replaceAll("-", "");

  }

}
Output:

Enter the length of random string to be generated: 12

A random string of 12 characters: 7gfdsfD798sf

Using Java 8 Stream

You can also generate a random alphanumeric string of fixed length using streams in Java.
A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters.

All the generated integer values are then converted into their corresponding characters which are then appended to a StringBuffer. The ints() method from java.util.Random class is used in the process that takes two integers as parameters and generates a stream of integers between those two integers including the starting integer but not the last one.

 

See this code demonstration below:

import java.util.Random;

public class RandomStrGenerator{

  public static void main(String[] args) throws IOException{

    Random rand = new Random();

    String str = rand.ints(48, 123)

                .filter(num -> (num<58 || num>64) && (num<91 || num>96))

    .limit(15)

    .mapToObj(c -> (char)c).collect(StringBuffer::new, StringBuffer::append, StringBuffer::append)

          .toString();

    System.out.println(“A random alphanumeric string: " + str);

  }

}
Output:

A random alphanumeric string: tCh5eb7osOTWY4v

If you wish to add the special characters that are in between 9 and A in the ASCII table (: ; < = > ? @) you can skip the next mentioned step as it is used to remove these characters to keep the string alphanumeric.

To remove these extra characters, the stream can be filtered with the filter() method to include ASCII values only ranging from 0-9, a-z and A-Z.

The limit() method is then also used to set the length of the string, it is set as  15 characters in the above example. It is very important as, without the limit() method, the stream will keep on generating integers infinitely. The mapToObj() method then converts the integer values to their corresponding characters.

At Last, the collect() method is used to collect the values generated by the stream into a StringBuffer using the append() method and the StringBuffer is then converted to a string with the toString() method.

Using Apache Commons Lang Library

The Apache Commons Lang library is a full-featured package of utility classes that extends the functionality of the Java API to a significant extent. It offers a variety of classes with functions for string and numbers manipulation, array creation and manipulation etc.

Also Read: A Guide to the Java ExecutorService

Apache Commons Lang library also offers the org.apache.commons.lang.RandomStringUtils class that provides a series of methods to generate a random string in Java.

 

Following four methods from the org.apache.commons.lang.RandomStringUtils class are used to generate different types of random strings:

– randomAlphabetic()

The randomAlphabetic() function takes an integer as an argument and returns a random string of that length consisting of random alphabets. The generated string has a mix of lower and upper case characters but if required, you can easily convert all the characters to lower or upper case with the use of simple .toUpper() or .toLower() methods.

– randomNumeric()

This function also takes an integer as an argument and returns a numeric string of that length.

– randomAlphanumeric()

It returns a random alphanumeric string consisting of upper case, lower case and digits. Here, the length is passed as an integer parameter, similar to the first two functions.

– random()

This class also offers the random() method. This method can be overloaded in numerous ways to generate all kinds of random strings but we will be looking into the simplest one. It takes an integer as an argument for the length of the string along with a string consisting of a set of characters.

The random string will be restricted to only those characters.  It allows you to fully customize your string by including selective lower case, upper case, digits or even special characters in the character set, based on your requirements.

 

See this demonstration below showing all four functions in action:

import org.apache.commons.lang.RandomStringUtils;

public class RandomStrGenerator {

  public static void main(String[] args) {

    String randomStr = RandomStringUtils.randomAlphabetic(20);

System.out.println("A random string of 20 alphabets: " + randomStr);

randomStr = RandomStringUtils.randomNumeric(5);

    System.out.println("A random string of 5 digits: " + randomStr);

randomStr = RandomStringUtils.randomAlphanumeric(10);

    System.out.println("A random string of 10 alphanumeric characters: " + randomString);

randomStr = RandomStringUtils.random (10, “qwert1234!@#”);

    System.out.println("A random string of 10 characters from “qwert1234!@#”: " + randomStr);

  }

}
Output:

A random string of 20 alphabets: OEfaRapxsdoEdIFYTfFm

A random string of 5 numbers: 64789

A random string of 10 characters from “qwert1234!@#” : #1w4q!re@3

 

In order to use Apache Commons Lang library, You will need to add the Maven dependency mentioned below:

<dependency>

    <groupId>org.apache.commons</groupId>

    <artifactId>commons-lang3</artifactId>

    <version>3.12.0</version>

</dependency>

Conclusion

We have covered some basic implementations of generating a random string in Java. These approaches were specifically selected based on their simplicity and low level of complexity but there are many more approaches available that you can try.

Using regular expressions, charset and other overloaded methods in org.apache.commons.lang.RandomStringUtils are a few of the other approaches.

new Java jobs



author

admin


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US