Generate a Random String of Specific Length in Java

  • Last updated Apr 25, 2024

This Java code snippet demonstrates how to generate a random string of a specific length. It utilizes the built-in functionalities of the Java programming language to create a random sequence of characters:

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class RandomManager {

    private static String UPPER_CHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static String LOWER_CHAR = "abcdefghijklmnopqrstuvwxyz";
    private static String NUMBER = "0123456789";
    private static String SPECIAL_CHAR = "!@#$*";
    private static String ALL_CHARS = UPPER_CHAR + LOWER_CHAR + NUMBER + SPECIAL_CHAR;

    private static SecureRandom random = new SecureRandom();

    public static String generateRandomString(int length) {

        StringBuilder randomBuilder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int randChar = random.nextInt(ALL_CHARS.length());
            char randUpChar = ALL_CHARS.charAt(randChar);
            randomBuilder.append(randUpChar);
        }
        List randomList = Arrays.asList(randomBuilder.toString().split(""));
        Collections.shuffle(randomList);
        return randomList.stream().collect(Collectors.joining());
    }

    public static void main(String args[]) {
        System.out.println(generateRandomString(10));
    }
}

In this code example, we have a class called RandomManager that makes use of the SecureRandom class from the java.security package. The purpose of using SecureRandom is to guarantee a high level of cryptographic security in generating random values.

The code defines several static string variables representing different character sets, such as uppercase letters, lowercase letters, numbers, and special characters. These character sets are then combined into a single string called ALL_CHARS.

The generateRandomString method takes an integer length as input and returns a randomly generated string of that length. Inside the method, a StringBuilder named randomBuilder is created to construct the random string.

A loop iterates length times, each time generating a random index within the range of ALL_CHARS.length(). This index is used to retrieve a character from ALL_CHARS, which is then appended to randomBuilder.

Next, the randomBuilder string is split into a list of individual characters using Arrays.asList and split(""). The Collections.shuffle method is called on the list to randomly reorder its elements.

Finally, the shuffled list is joined back into a single string using the Collectors.joining method from the Java 8 Stream API. The resulting string represents the randomly generated string of the specified length and is returned by the generateRandomString method.

In the main method, an example usage of the generateRandomString method is demonstrated by generating and printing a random string of length 10.

The output of the above code is as follows:

6AudUGGkXt