Here you can use my method for generating Random String

protected String getSaltString() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;

    }

The above method from my bag using to generate a salt string for login purpose.

Answer from Suresh Atta on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › generate-random-string-of-given-size-in-java
Generate random String of given size in Java - GeeksforGeeks
July 11, 2025 - // Java program generate a random AlphaNumeric String // using Math.random() method public class RandomString { // function to generate a random string of length n static String getAlphaNumericString(int n) { // choose a Character random from ...
🌐
Baeldung
baeldung.com › home › java › java string › java – generate random string
Java - Generate Random String | Baeldung
May 11, 2024 - @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.
🌐
CodeJava
codejava.net › coding › generate-random-strings-examples
Generate Random Strings in Java Examples
Then we create a String object from the byte array, which results in a random string.Since a byte can have any value from -128 to 127, the generated string can contain non-visible characters. That means this code example cannot be used in practice, rather it gives you the basic idea of how to write code for generating random strings in Java.Also note that the java.util.Random class generates pseudorandom numbers, or fake random.
🌐
Programiz
programiz.com › java-programming › examples › generate-random-string
Java Program to Create random strings
import java.util.Random; class ... // append the character to string builder sb.append(randomChar); } String randomString = sb.toString(); System.out.println("Random String is: " + randomString); } }...
🌐
Java By Examples
javabyexamples.com › generate-random-string-in-java
Generate Random String in Java
Firstly, we'll examine an approach that relies on java.util.Random class: public void randomUsingPlain(int length) { final Random random = new Random(); final byte[] array = new byte[length]; random.nextBytes(array); final String generated = new String(array, StandardCharsets.UTF_8); ...
Top answer
1 of 16
1642

Algorithm

To generate a random string, concatenate characters drawn randomly from the set of acceptable symbols until the string reaches the desired length.

Implementation

Here's some fairly simple and very flexible code for generating random identifiers. Read the information that follows for important application notes.

public class RandomString {

    /**
     * Generate a random string.
     */
    public String nextString() {
        for (int idx = 0; idx < buf.length; ++idx)
            buf[idx] = symbols[random.nextInt(symbols.length)];
        return new String(buf);
    }

    public static final String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static final String lower = upper.toLowerCase(Locale.ROOT);

    public static final String digits = "0123456789";

    public static final String alphanum = upper + lower + digits;

    private final Random random;

    private final char[] symbols;

    private final char[] buf;

    public RandomString(int length, Random random, String symbols) {
        if (length < 1) throw new IllegalArgumentException();
        if (symbols.length() < 2) throw new IllegalArgumentException();
        this.random = Objects.requireNonNull(random);
        this.symbols = symbols.toCharArray();
        this.buf = new char[length];
    }

    /**
     * Create an alphanumeric string generator.
     */
    public RandomString(int length, Random random) {
        this(length, random, alphanum);
    }

    /**
     * Create an alphanumeric strings from a secure generator.
     */
    public RandomString(int length) {
        this(length, new SecureRandom());
    }

    /**
     * Create session identifiers.
     */
    public RandomString() {
        this(21);
    }

}

Usage examples

Create an insecure generator for 8-character identifiers:

RandomString gen = new RandomString(8, ThreadLocalRandom.current());

Create a secure generator for session identifiers:

RandomString session = new RandomString();

Create a generator with easy-to-read codes for printing. The strings are longer than full alphanumeric strings to compensate for using fewer symbols:

String easy = RandomString.digits + "ACEFGHJKLMNPQRUVWXYabcdefhijkprstuvwx";
RandomString tickets = new RandomString(23, new SecureRandom(), easy);

Use as session identifiers

Generating session identifiers that are likely to be unique is not good enough, or you could just use a simple counter. Attackers hijack sessions when predictable identifiers are used.

There is tension between length and security. Shorter identifiers are easier to guess, because there are fewer possibilities. But longer identifiers consume more storage and bandwidth. A larger set of symbols helps, but might cause encoding problems if identifiers are included in URLs or re-entered by hand.

The underlying source of randomness, or entropy, for session identifiers should come from a random number generator designed for cryptography. However, initializing these generators can sometimes be computationally expensive or slow, so effort should be made to re-use them when possible.

Use as object identifiers

Not every application requires security. Random assignment can be an efficient way for multiple entities to generate identifiers in a shared space without any coordination or partitioning. Coordination can be slow, especially in a clustered or distributed environment, and splitting up a space causes problems when entities end up with shares that are too small or too big.

Identifiers generated without taking measures to make them unpredictable should be protected by other means if an attacker might be able to view and manipulate them, as happens in most web applications. There should be a separate authorization system that protects objects whose identifier can be guessed by an attacker without access permission.

Care must be also be taken to use identifiers that are long enough to make collisions unlikely given the anticipated total number of identifiers. This is referred to as "the birthday paradox." The probability of a collision, p, is approximately n2/(2qx), where n is the number of identifiers actually generated, q is the number of distinct symbols in the alphabet, and x is the length of the identifiers. This should be a very small number, like 2‑50 or less.

Working this out shows that the chance of collision among 500k 15-character identifiers is about 2‑52, which is probably less likely than undetected errors from cosmic rays, etc.

Comparison with UUIDs

According to their specification, UUIDs are not designed to be unpredictable, and should not be used as session identifiers.

UUIDs in their standard format take a lot of space: 36 characters for only 122 bits of entropy. (Not all bits of a "random" UUID are selected randomly.) A randomly chosen alphanumeric string packs more entropy in just 21 characters.

UUIDs are not flexible; they have a standardized structure and layout. This is their chief virtue as well as their main weakness. When collaborating with an outside party, the standardization offered by UUIDs may be helpful. For purely internal use, they can be inefficient.

2 of 16
903

Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use uuid.replace("-", "")

import java.util.UUID;

public class randomStringGenerator {
    public static void main(String[] args) {
        System.out.println(generateString());
    }

    public static String generateString() {
        String uuid = UUID.randomUUID().toString();
        return "uuid = " + uuid;
    }
}

Output

uuid = 2d7428a6-b58c-4008-8575-f05549f16316
🌐
Java67
java67.com › 2018 › 01 › how-to-create-random-alphabetic-or-alphanumeric-string-java.html
How to Create Random Alphabetic or AlphaNumeric String of given length in Java? SecureRandom Example | Java67
This means that it can not be used for session identifiers or security-sensitive keys since an attacker can easily predict what the generated session identifiers are at any given time. The JDK 7 introduced a newer SecureRandom class which provides better security as compared to java.util.Random and provides a cryptographically strong random number generator. I'll show you can use that to generate an alphabetic, numeric, or alphanumeric string of a given length in Java.
🌐
Reddit
reddit.com › r/javahelp › how can i generate a random string of a certain amount of letters?
How can I generate a random string of a certain amount of letters? : r/javahelp
August 10, 2022 - Well, one of the simplest ways would be a StringBuilder or just a regular String, a for loop and a random.
Find elsewhere
🌐
Mkyong
mkyong.com › home › java › java – how to generate a random string
Java - How to generate a random String - Mkyong.com
May 4, 2019 - package com.mkyong; import java.security.SecureRandom; public class RandomExample { private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz"; private static final String CHAR_UPPER = CHAR_LOWER.toUpperCase(); private static final String NUMBER = "0123456789"; private static final String DATA_FOR_RANDOM_STRING = CHAR_LOWER + CHAR_UPPER + NUMBER; private static SecureRandom random = new SecureRandom(); public static void main(String[] args) { System.out.println("String : " + DATA_FOR_RANDOM_STRING); for (int i = 0; i < 5; i++) { System.out.println("result : " + generateRandomString(
🌐
TutorialsPoint
tutorialspoint.com › generate-a-random-string-in-java
Generate a random string in Java
import java.util.Random; public class Demo { public static void main(String[] args) { String[] strArr = { "P", "Q", "R", "S","T", "U", "V", "W" }; Random rand = new Random(); int res = rand.nextInt(strArr.length); System.out.println("Displaying a random string = " + strArr[res]); } }
🌐
Coderanch
coderanch.com › t › 35392 › Generate-random-strings
Generate random strings (Programming Diversions forum at Coderanch)
The len > 1 often terminates the loop for small String-lengths (M) or small numChars, which leeds to too much Strings of len=1. It was reduced by Peter Chase (having numChars=94 in mind) this way: Well - this will work for numChars=2, if it is adjusted: and repeated until (len != 0) And using that, I generated a complete solution, which generates 20 000 - 30 000 Strings of maxlen=300 and numChars=94 per second on my 2Ghz-Laptop. Here it is (with a little debug-code included): Statistic for 2Ghz Pentium: time java -Xmx384M 300 94 tuple Test with small values for Stringlength and character-set-size: My favorite solution would have been: Pseudocode, of course.
🌐
TutorialsPoint
tutorialspoint.com › different-ways-to-generate-string-by-using-characters-and-numbers-in-java
Different Ways to Generate String by using Characters and Numbers in Java
The Random class approach is useful when we need to generate a random string of a given length. It is simple and easy to implement but may not be the most efficient for generating large strings. The Apache Commons Lang library approach is a comprehensive and powerful approach that provides a lot of flexibility and customization options. It is useful when we need to generate a string that follows a specific pattern or format. Generating strings by using characters and numbers is a common task in Java programming, and we have many different approaches to achieve this.
🌐
Programming.Guide
programming.guide › java › generating-a-random-string.html
Java: Generating a random String (password, booking reference, etc) | Programming.Guide
int length = 8; String digits = "0123456789"; String specials = "~=+%^*/()[]{}/!@#$?|"; String all = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + digits + specials; Random rnd = new Random(); List<String> result = new ArrayList<>(); Consumer<String> appendChar = s -> result.add("" + s.charAt(rnd.nextInt(s.length()))); appendChar.accept(digits); appendChar.accept(specials); while (result.size() < length) appendChar.accept(all); Collections.shuffle(result, rnd); String str = String.join("", result);
🌐
Java String
javastring.net › home › how to easily generate random string in java
How to Easily Generate Random String in Java
August 9, 2019 - Repeat steps 2 and 3 until the StringBuilder size is equal to the required length of the random string. Return the random string using the StringBuilder toString() method. Here is the utility method implementation to generate a random string based on the above algorithm. We are getting the random string length from the user input. package net.javastring.strings; import java.util.Random; import java.util.Scanner; public class GenerateRandomString { public static void main(String[] args) { String asciiUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String asciiLowerCase = asciiUpperCase.toLowerCase();
🌐
Our Code World
ourcodeworld.com › articles › read › 964 › how-to-generate-random-alphanumeric-strings-with-a-custom-length-in-java
How to generate random alphanumeric strings with a custom length in Java | Our Code World
June 14, 2019 - Random string: iU5OHBDJ34 Random string: PDfkpDQMYz Random string: 7OXEtv4PTT Random string: CvYpocv3bE Random string: yyBeOe5cee · If you don't want to implement by your own this feature, you can rely on a third party package, specifically one of Apache. The standard Java libraries fail to provide enough methods for manipulation of its core classes.
🌐
Medium
medium.com › beingcoders › ways-to-generate-random-string-in-java-6d3b1d964c02
Ways to Create a Random String in Java: Ultimate Guide with Scenarios | BeingCoders
March 16, 2025 - Explore various methods to generate random strings in Java, from basic to advanced techniques, with real-world examples for different…
🌐
Xperti
xperti.io › home › generate random string in java
Easiest Ways To Generate A Random String In Java
May 9, 2022 - 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().
Top answer
1 of 6
4

What about using apache commons? It has a RandomStringUtils class that provides exactly the functionality you're looking for, but in the end it loops too...

org.apache.commons.lang3.RandomStringUtils#randomAlphanumeric(int count)

From JavaDoc

Creates a random string whose length is the number of characters specified.

Characters will be chosen from the set of alpha-numeric characters.

Parameters:
    count - the length of random string to create
Returns:
    the random string

If it doesn't need to be random there is another, cheaper method in Stringutils:

org.apache.commons.lang3.StringUtils#repeat(char, int)

But in the end it too loops...

From JavaDoc

Returns padding using the specified delimiter repeated to a given length.

 StringUtils.repeat('e', 0)  = ""
 StringUtils.repeat('e', 3)  = "eee"
 StringUtils.repeat('e', -2) = ""


Note: this method doesn't not support padding with Unicode Supplementary Characters as they require a pair of chars to be represented. If you are needing to support full I18N of your applications consider using repeat(String, int) instead.

Parameters:
    ch - character to repeat
    repeat - number of times to repeat char, negative treated as zero
Returns:
    String with repeated character
See Also:
    repeat(String, int)
2 of 6
2

If you're only concerned about the string's length, you can just do this:

String str = new String(new char[SIZE]);

This is useful, for example, when you want to test if a given method fails when it is given a string of a specific length.