Generate a Random String of Specific Length in Java

Here is a Java code to generate a random String of specific length:


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 = "[email protected]#$*";
    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<String> 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));
    }
}
Output:
6AudUGGkXt