Java – Generate Random String

1. Introduction

In this tutorial, we’re going to learn how to generate a random string in Java, first using the standard Java libraries, then using a Java 8 variant, and finally using the Apache Commons Lang library.

This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

2. Generate Random Unbounded String With Plain Java

Let’s start simple and generate a random String bounded to 7 characters:

@Test
public void givenUsingPlainJava_whenGeneratingRandomStringUnbounded_thenCorrect() {
    byte[] array = new byte[7]; // length is bounded by 7
    new Random().nextBytes(array);
    String generatedString = new String(array, Charset.forName("UTF-8"));

    System.out.println(generatedString);
}

Keep in mind that the new string will not be anything remotely alphanumeric.

3. Generate Random Bounded String With Plain Java

Next let’s look at creating a more constrained random string; we’re going to generate a random String using lowercase alphabetic letters and a set length:

@Test
public void givenUsingPlainJava_whenGeneratingRandomStringBounded_thenCorrect() {
 
    int leftLimit = 97; // letter 'a'
    int rightLimit = 122; // letter 'z'
    int targetStringLength = 10;
    Random random = new Random();
    StringBuilder buffer = new StringBuilder(targetStringLength);
    for (int i = 0; i < targetStringLength; i++) {
        int randomLimitedInt = leftLimit + (int) 
          (random.nextFloat() * (rightLimit - leftLimit + 1));
        buffer.append((char) randomLimitedInt);
    }
    String generatedString = buffer.toString();

    System.out.println(generatedString);
}

4. Generate Random Alphabetic String With Java 8

Now let’s use Random.ints, added in JDK 8, to generate an alphabetic String:

@Test
public void givenUsingJava8_whenGeneratingRandomAlphabeticString_thenCorrect() {
    int leftLimit = 97; // letter 'a'
    int rightLimit = 122; // letter 'z'
    int targetStringLength = 10;
    Random random = new Random();

    String generatedString = random.ints(leftLimit, rightLimit + 1)
      .limit(targetStringLength)
      .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
      .toString();

    System.out.println(generatedString);
}

5. Generate Random Alphanumeric String With Java 8

Then we can widen our character set in order to get an alphanumeric String:

@Test
public void givenUsingJava8_whenGeneratingRandomAlphanumericString_thenCorrect() {
    int leftLimit = 48; // numeral '0'
    int rightLimit = 122; // letter 'z'
    int targetStringLength = 10;
    Random random = new Random();

    String generatedString = random.ints(leftLimit, rightLimit + 1)
      .filter(i -> (i <= 57 || i >= 65) && (i <= 90 || i >= 97))
      .limit(targetStringLength)
      .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append)
      .toString();

    System.out.println(generatedString);
}

We used the filter method above to leave out Unicode characters between 65 and 90 in order to avoid out of range characters.

6. Generate Bounded Random String With Apache Commons Lang

The Commons Lang library from Apache helps a lot with random string generation. Let’s take a look at generating a bounded String using only letters:

@Test
public void givenUsingApache_whenGeneratingRandomStringBounded_thenCorrect() {
 
    int length = 10;
    boolean useLetters = true;
    boolean useNumbers = false;
    String generatedString = RandomStringUtils.random(length, useLetters, useNumbers);

    System.out.println(generatedString);
}

So instead of all the low-level code in the Java example, this one is done with a simple one-liner.

7. Generate Alphabetic String With Apache Commons Lang

Here is another very simple example, this time a bounded String with only alphabetic characters, but without passing boolean flags into the API:

@Test
public void givenUsingApache_whenGeneratingRandomAlphabeticString_thenCorrect() {
    String generatedString = RandomStringUtils.randomAlphabetic(10);

    System.out.println(generatedString);
}

8. Generate Alphanumeric String With Apache Commons Lang

Finally, we have the same random bounded String, but this time numeric:

@Test
public void givenUsingApache_whenGeneratingRandomAlphanumericString_thenCorrect() {
    String generatedString = RandomStringUtils.randomAlphanumeric(10);

    System.out.println(generatedString);
}

And there we have it, creating bounded and unbounded strings with either plain Java, a Java 8 variant, or the Apache Commons Library.

9. Conclusion

Through different implementation methods, we were able to generate bound and unbound strings using plain Java, a Java 8 variant, or the Apache Commons Library.

In these Java examples, we used java.util.Random, but one point worth mentioning is that it is not cryptographically secure. Consider using java.security.SecureRandom instead for security-sensitive applications.

The implementation of all of these examples and snippets can be found in the GitHub project. This is a Maven-based project so it should be easy to import and run.

Related posts:

Java Program to Implement Miller Rabin Primality Test Algorithm
Spring AMQP in Reactive Applications
Java Program to Find Number of Articulation points in a Graph
Spring Boot - Rest Controller Unit Test
Java Program to Create a Balanced Binary Tree of the Incoming Data
Java Program to Implement Merge Sort Algorithm on Linked List
Các chương trình minh họa sử dụng Cấu trúc điều khiển trong Java
Logout in an OAuth Secured Application
Function trong Java 8
Converting Between an Array and a Set in Java
Implementing a Binary Tree in Java
JavaScript Methods of RegExp and String
Java Program to Find Maximum Element in an Array using Binary Search
Java Program to Implement PriorityBlockingQueue API
Java Program to Implement Randomized Binary Search Tree
Java Program to Perform Partial Key Search in a K-D Tree
Quick Guide to java.lang.System
Serve Static Resources with Spring
How to Delay Code Execution in Java
OAuth2 for a Spring REST API – Handle the Refresh Token in AngularJS
Abstract class và Interface trong Java
Java Program to Find Strongly Connected Components in Graphs
Spring Data MongoDB Transactions
Java Program to Find Location of a Point Placed in Three Dimensions Using K-D Trees
Custom Exception trong Java
Hướng dẫn sử dụng lớp Console trong java
Java Program to implement Priority Queue
Cài đặt và sử dụng Swagger UI
Hướng dẫn sử dụng Lớp FilePermission trong java
Java Program to Find a Good Feedback Vertex Set
Autoboxing và Unboxing trong Java
A Guide to System.exit()