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
🌐
Baeldung
baeldung.com › home › java › java string › java – generate random string
Java - Generate Random String | Baeldung
May 11, 2024 - Generate Bounded and Unbounded Random Strings using plain Java and the Apache Commons Lang library.
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.9 › org › apache › commons › lang3 › RandomStringUtils.html
RandomStringUtils (Apache Commons Lang 3.9 API)
This method has exactly the same semantics as random(int,int,int,boolean,boolean,char[],Random), but instead of using an externally supplied source of randomness, it uses the internal static Random instance. ... ArrayIndexOutOfBoundsException - if there are not (end - start) + 1 characters in the set array. public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random)
🌐
GeeksforGeeks
geeksforgeeks.org › java › generate-random-string-of-given-size-in-java
Generate random String of given size in Java - GeeksforGeeks
July 11, 2025 - Method 1: Using Math.random() Here the function getAlphaNumericString(n) generates a random number of length a string. This number is an index of a Character and this Character is appended in temporary local variable sb.
🌐
CodeJava
codejava.net › coding › generate-random-strings-examples
Generate Random Strings in Java Examples
Random String #1: !`;u!k=|Vc Random String #2: %%xB\B25ryhg|zS Random String #3: K/IzJ'}e@z$Vo%`'.Il)You can use this code example to generate random strong passwords. You can use the java.util.UUID class to generate random strings that are kind of Universally Unique Identifier (UUID).
🌐
Programiz
programiz.com › java-programming › examples › generate-random-string
Java Program to Create random strings
import java.util.Random; class ... = alphabet.charAt(index); // append the character to string builder sb.append(randomChar); } String randomString = sb.toString(); System.out.println("Random String is: " + randomString); } }...
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
🌐
Reddit
reddit.com › r/askprogramming › [java] generating a random string with certain conditions
r/AskProgramming on Reddit: [Java] Generating a random string with certain conditions
August 10, 2020 -

Hello all,

I am currently working on a JavaFX project for school that serves as an extremely elementary password validation program. The conditions of a valid password is for it to contain at least ONE upper case letter, ONE lower case letter, and TWO digits/numbers.

Along with having to verify whether user inputted passwords meet these conditions or not, the program must also have the ability to generate a valid password for the user at the click of the button.

I have gotten the program to a point where users can generate a random string. However, I have been unable to get it to a point where the randomly generated string will have an upper case, a lower case, and two digits everytime.

Here is my current code for the portion of the program pertaining to generating a password: https://drive.google.com/file/d/1V8V4Ia0ju6EgHNl6Yg2fHd32BRNztEOz/view?usp=sharing

I've created a for loop that will go through each character of the generated string and count whether the character is upper case, lower case, or a digit. I've attempted to wrap this in a do while loop so that the program continuously generates strings until it produces one that meets the conditions however it does not seem to work as intended.

I have very intermediate knowledge so any guidance will be genuinely and greatly appreciated.

Top answer
1 of 1
2
I see three issues with your implementation. The first is that upper, lower, and digit are never reset to 0. This means that if the password from the first iteration has both upper and lowercase letters and the second is all digits then you'll get the all-digit password. Annoyingly you can't just move the counts inside the loop since that puts them out of scope for the condition. A better way to structure this is to put all of the checking logic in its own function (since you'll need that functionality to validate user-input passwords anyway), at which point your loop can be do { generatedPassword = RandomStringUtils.randomAlphanumeric(count); } while ( !validPassword(generatedPassword));. The second issue is that the if statement you have in the loop is completely unnecessary. At the end of the loop the condition by the while statement is going to trigger anyway, and at the start of the next loop the password will be regenerated. This entire block can be deleted and won't be missed. The third issue is that the condition you have isn't correct. The condition for a password being valid is upper >= 1 && lower >= 1 && digit >= 2. You've properly negated each of the parts into upper < 1, lower < 1, and digit < 2, but to negate a compound boolean expression like this you also swap and with or. The proper condition is upper < 1 || lower < 1 || digit < 2. As written the loop will only retry if you manage to get a password that has no upper or lowercase characters and less than 2 digits! More generally, for the problem of "generate X such that Y" one of the standard approaches is the kind you've gravitated towards here, where you just generate a random X and check if Y, then regenerate X as many times as you need to until Y becomes true. This approach works well when most X are Y. In this case that's likely, depending on the value of count. If you wanted to go for a more explicit route then you could do something like: if(count < 4) { throw new /*pick your favorite exception*/; char password[count]; password[0] = //random uppercase letter password[1] = //random lowercase letter password[2] = //random digit password[3] = //random digit for(int i = 4; i < count; ++i) { password[i] = //random alphanumeric; } //shuffle the positions of the characters within the array, possibly using Collections.shuffle return new String(password); //package the char array into a String As a caveat: I haven't been a Java developer in years so I'm out of practice with java idioms these days. The above is an example of a strategy for avoiding the guess and check approach, not a recommendation for a specific approach. Finally, if you're making passwords that'll actually be used for something please don't use a default random number generator. If this is purely for educational purposes you're fine.
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › java › examples › create-random-strings
Java Program to Create random strings | Vultr Docs
November 25, 2024 - It builds a string of the specified length by randomly selecting characters from the predefined characterSet. The use of StringBuilder ensures that the string construction is efficient.
🌐
Mkyong
mkyong.com › home › java › java – how to generate a random string
Java - How to generate a random String - Mkyong.com
May 4, 2019 - 1.1 Generate a random alphanumeric String [a-ZA-Z0-9], with a length of 8. ... package com.mkyong; import java.security.SecureRandom; public class RandomExample { private static final String CHAR_LOWER = "abcdefghijklmnopqrstuvwxyz"; private ...
🌐
Apache Commons
commons.apache.org › proper › commons-text › javadocs › api-release › org › apache › commons › text › RandomStringGenerator.html
RandomStringGenerator (Apache Commons Text 1.9 API)
Generates random Unicode strings containing the specified number of code points. Instances are created using a builder class, which allows the callers to define the properties of the generator.
🌐
GitHub
github.com › moznion › java-random-string
GitHub - moznion/java-random-string: Generate random strings based on a pattern
"a5B123 18X") String randomString = generator.generateByRegex("\\w+\\d*\\s[0-9]{0,3}X");
Starred by 23 users
Forked by 9 users
Languages   Java
🌐
Java By Examples
javabyexamples.com › generate-random-string-in-java
Generate Random String in Java
Here, we're creating a Random instance that populates a byte array. Note that we're initializing the array with the given length. After we have the byte array populated, we're creating a String from it using UTF-8. One important note is that the resulting String can contain any character - not limited to numbers or Latin alphabetic characters: ... Another approach relying on java.util.Random uses its Stream support.
🌐
Apache Commons
commons.apache.org › proper › commons-lang › javadocs › api-3.8 › org › apache › commons › lang3 › RandomStringUtils.html
RandomStringUtils (Apache Commons Lang 3.8 API)
This constructor is public to permit tools that require a JavaBean instance to operate. ... Creates a random string whose length is the number of characters specified.
🌐
Xperti
xperti.io › home › generate random string in java
Easiest Ways To Generate A Random String In Java
May 9, 2022 - 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 ...
🌐
LambdaTest Community
community.lambdatest.com › general discussions
How to generate a random alphanumeric string in Java? - LambdaTest Community
January 11, 2025 - How can I generate a random string in Java with characters A-Z and 0-9? I need to create a random 17-character long ID, like “AJB53JHS232ERO0H1”, where both the letters and numbers are randomized. I initially thought of creating an array with the letters A-Z and using a ‘check’ variable to randomly choose between letters and numbers, with the logic inside a loop: Randomize ‘check’ to 1-2. If check == 1, pick a random letter from the array.
🌐
Apache Commons
commons.apache.org › proper › commons-lang › apidocs › org › apache › commons › lang3 › RandomStringUtils.html
RandomStringUtils (Apache Commons Lang 3.20.0 API)
java.lang.Object · org.apache... Object · Generates random Strings. Use secure() to get the singleton instance based on SecureRandom() which uses a secure random number generator implementing the default random number algorithm....
🌐
Coderanch
coderanch.com › t › 382532 › java › generate-random-string
how to generate random string...? (Java in General forum at Coderanch)
More a beginner's question. Chars are numbers, you do know that? So you can create a random number in the requisite range (for lower-case letters 0x61 to 0x7a inclusive) and cast it to a char.