You can use RandomStringUtils

import org.apache.commons.lang.RandomStringUtils;
public class RandomStringUtilsTrial {
  public static void main(String[] args) {
    System.out.print("8 char string  >>>");
    System.out.println(RandomStringUtils.random(8, true, true));

  }
}
Answer from bilash.saha 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.
Discussions

java - How to generate a random alpha-numeric string - Stack Overflow
I've been looking for a simple Java algorithm to generate a pseudo-random alpha-numeric string. In my situation it would be used as a unique session/key identifier that would "likely" be unique over More on stackoverflow.com
🌐 stackoverflow.com
java - Generate unique random strings considering collisions - Code Review Stack Exchange
I'm coding a random strings generator. It's working, but I'm not sure if this is efficient. /** * @param n total number of strings to generate * @param length length of generated str... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
December 26, 2022
java - How to generate a random unique string with more than 2^30 combination. I also wanted to reverse the process. Is this possible? - Stack Overflow
I have a string which contains 3 elements: a 3 digit code (example: SIN, ABD, SMS, etc) a 1 digit code type (example: 1, 2, 3, etc) a 3 digit number (example: 500, 123, 345) Example string: SIN1500, More on stackoverflow.com
🌐 stackoverflow.com
How to generate a random String in Java - Stack Overflow
If number of students exceeds 10^7, you'll have no way to assign a unique number to each. ... Save this answer. Show activity on this post. Generating a random string of characters is easy - just use java.util.Random and a string containing all the characters you want to be available, e.g. More on stackoverflow.com
🌐 stackoverflow.com
🌐
CodeJava
codejava.net › coding › generate-random-strings-examples
Generate Random Strings in Java Examples
January 13, 2023 - You can use the java.util.UUID class to generate random strings that are kind of Universally Unique Identifier (UUID).
🌐
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…
🌐
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); } }...
🌐
Mkyong
mkyong.com › home › java › java – how to generate a random string
Java - How to generate a random String - Mkyong.com
May 4, 2019 - Generate a random String of 32 alphanumeric characters (hexadecimal) and 4 hyphens, read this UUID format ... package com.mkyong; import java.util.UUID; public class UUIDExample { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println(generateRandomStringByUUIDNoDash()); } for (int i = 0; i < 10; i++) { System.out.println(generateRandomStringByUUIDNoDash()); } } public static String generateRandomStringByUUID() { return UUID.randomUUID().toString(); } public static String generateRandomStringByUUIDNoDash() { return UUID.randomUUID().toString().replace("-", ""); } }
🌐
Javacodepoint
javacodepoint.com › generate-random-string-in-java
Java Random String | Generate random Strings - Javacodepoint
November 18, 2020 - In this example, we are going to generate random strings in some specific patterns. For example, orderId= “OD_6578400012”. Here for orderId, the pattern is OD_XXXXXXXXXX, meaning OD_ is a static prefix followed by 10 random digits. Let’s see the Java program below:
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
Find elsewhere
🌐
Medium
medium.com › @ganeshbn › how-to-generate-a-unique-string-in-java-without-third-party-libraries-a0b9691b2b93
How to Generate a Unique String in Java Without Third-Party Libraries | by GN | Medium
January 19, 2025 - Java provides the UUID class in the java.util package to generate universally unique identifiers. import java.util.UUID; public class UniqueStringGenerator { public static void main(String[] args) { String uniqueString = UUID.randomUUID().t...
🌐
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 ...
🌐
Liberian Geek
liberiangeek.net › home › how-to/tips › how to generate a random string in java?
How to Generate a Random String in Java? | Liberian Geek
December 19, 2023 - The output confirms that a unique alphabetic random String has been generated after each execution cycle: The custom regular expression can be used with the “Random” class to generate a random String of specific characters.
🌐
GitHub
github.com › aventrix › jnanoid
GitHub - aventrix/jnanoid: A unique string ID generator for Java. · GitHub
February 4, 2026 - A unique string ID generator for Java. JNanoID uses Java’s SecureRandom to generate cryptographically strong random IDs with a proper distribution of characters.
Starred by 516 users
Forked by 58 users
Languages   Java
Top answer
1 of 2
1

Your requirements are very unclear. So I'm going to restrict my answer to generalities:

There are functions called cryptographic hash functions that will map from an arbitrary sequence of bytes to a "hash", with the property that the probability of any two related inputs giving the same output is vanishingly small. However, cryptographic hash functions are (by design) not reversible ... by design.

A mapping from one "space" of Strings to another that is reversible, can be implemented in two ways:

  • You can generate arbitrary Strings as the mapped Strings, and use data structures such as a hash tables to store the forward and reverse mappings.

  • You can use a cryptographic hash function to generate the mapped Strings, and use data structures such as a hash tables to store the reverse mappings.

  • You can use a reversible function to transform between the original and mapped Strings. This has the problem that the mapping is likely to be be easy to reverse engineer.

An example of the latter might be to turn the original String into bytes and then base64 encode it. Or even more trivially, you could insert a random character between each character in the input string. (Obviously, transformations like these can be reverse engineered in a few minutes ... given enough examples. So one has to doubt the wisdom of this approach.)

Without better requirements, it is unclear which (if any) of these approaches is what you need.

2 of 2
0

I've written a Ruby tool that does what you need. (Sorry it isn't Java, but my Java is over a decade old by now. But the general idea should port to Java without hassle.)

In short, the given input string (7 bytes) is compressed into a number between 0 and 175_760_000 (28 bits). A 32 bit random number is prepended, making a 60 bit integer, which is encoded into a 10-character output string.

My earlier math was wrong; since your input is only 28 bits long and your desired output is 60 bits long, that leaves 32 bits for adding roughly two billion random permutations. I mistyped when performing my calculations.

#!/usr/bin/ruby -w
START_A = "A"[0]
START_a = "a"[0]
START_0 = "0"[0]
CODEMASK = ((1 << 28) - 1) # turn on lower 28 bits
RANDOMMASK = ((1 << 60) - 1) & ~ CODEMASK # turn on upper 32 bits


def compress(line)
    a, b, c, h, i, j, k = line.chomp().each_char().entries()
    a, b, c = a[0], b[0], c[0]
    small_a, small_b, small_c = a - START_A, b - START_A, c - START_A
    letters = (small_a * 26**2) + (small_b * 26) + small_c
    h, i, j, k = Integer(h), Integer(i), Integer(j), Integer(k)
    number = letters * 10_000 + h*1000 + i*100 + j*10 + k
end

def uncompress(number)
    k = number % 10
    number /= 10
    j = number % 10
    number /= 10
    i = number % 10
    number /= 10
    h = number % 10
    number /= 10
    small_c = number % 26
    number /= 26
    small_b = number % 26
    number /= 26
    small_a = number % 26
    number /= 26
    if (number != 0)
            raise "input wasn't generated with compress()"
    end
    a, b, c = small_a + START_A, small_b + START_A, small_c + START_A
    [a.chr(), b.chr(), c.chr(), h.to_s(), i.to_s(), j.to_s(), k.to_s()].join()
end

def add_random(number)
    (rand(2**31) << 28) + number
end 

def remove_random(number)
    [number & CODEMASK, number & RANDOMMASK]
end

def to_output(number)
    a = []
    begin
            a << transform_out(number % 62)
            number /= 62
    end while(number > 0)
    a.reverse().join()
end

def from_output(string)
    num = 0
    string.each_char() do |c|
            num *= 62
            num += transform_in(c)
    end     
    num
end

def transform_out(small)
    if (small < 0 || small > 61)
            raise "small should be between 0 and 61, inclusive"
    end
    if (small < 26)
            out = START_A+small
    elsif (small < 52)
            out = START_a+(small-26)
    else
            out = START_0+(small-52)
    end
    out.chr()
end

def transform_in(char)
    if (/^[A-Za-z0-9]$/ !~ char)
            raise "char should be A-Z, a-z, or 0-9, inclusive"
    end
    num = char[0]
    out = case num
    when START_A .. START_A+26 then num - START_A
    when START_a .. START_a+26 then (num - START_a) + 26
    when START_0 .. START_0+10 then (num - START_0) + 52
    end

    out
end


begin
    while(line = DATA.readline()) do
            line.chomp!()
            c = compress(line)
            a = add_random(c)
            output = to_output(a)
            input = from_output(output)
            new_c, r = remove_random(input)
            u = uncompress(new_c)

            printf("original input: %s\n compressed: %d\n after adding random amount: %d\n *output: %s\n *input: %s\n random amount added: %d\n after removing random amount: %d\nuncompressed: %s\n", line, c, a, output, input, r, new_c, u)
    end
rescue EOFError => e
end


__END__
AAA0000
SIN1500
ABD2123
SMS3345
ZZZ9999

Running the program with the five inputs given at the bottom results in this output:

$ ./compress.rb
original input: AAA0000
 compressed: 0
 after adding random amount: 508360097408221184
 *output: liSQkzXL1G
 *input: 508360097408221184
 random amount added: 508360097408221184
 after removing random amount: 0
uncompressed: AAA0000
original input: SIN1500
 compressed: 123891500
 after adding random amount: 421470683267231532
 *output: fIVFtX9at2
 *input: 421470683267231532
 random amount added: 421470683143340032
 after removing random amount: 123891500
uncompressed: SIN1500
original input: ABD2123
 compressed: 292123
 after adding random amount: 414507907112269083
 *output: emb6JfDhUH
 *input: 414507907112269083
 random amount added: 414507907111976960
 after removing random amount: 292123
uncompressed: ABD2123
original input: SMS3345
 compressed: 124983345
 after adding random amount: 383242064398325809
 *output: cTPpccLAvn
 *input: 383242064398325809
 random amount added: 383242064273342464
 after removing random amount: 124983345
uncompressed: SMS3345
original input: ZZZ9999
 compressed: 175759999
 after adding random amount: 27149937199932031
 *output: CAVf14tiRh
 *input: 27149937199932031
 random amount added: 27149937024172032
 after removing random amount: 175759999
uncompressed: ZZZ9999

The lines you're really looking for are original input, *output, and uncompressed. Your client has the original input lines, after using the to_output(add_random(compress(input))) you will get the ten-character A-Za-z0-9 output in the *output line. You hand that to users, and it's a magic token of some sort. Then when it is time to validate them, you use remove_random(from_output(user_string)) to discover both the random value added to the string and an integer that you can hand to uncompress().

One very important note: The input AAA0000 is stored in plaintext in the lower 28 bits. The random number is stored in plaintext in the upper 32 bits. This is simply an obfuscation of the original inputs, it wouldn't be hard for someone to discover the pattern if they have two inputs and outputs. Heck, they might even correctly guess the algorithm given only a single input and output.

If you need this to be cryptographically strong, then you've still got some work ahead of you :) but that might be as easy as XORing the intermediate 60 bit number with rc4 output of the username or something like that.

Short Explanation

Your input strings can be interpreted as integers, but with a twist: the first three 'digits' are in base 26, the next four digits are in base 10. The number will be less than 175_760_000. Uniquely storing numbers between 0 and 175_760_000 requires 28 bits. Your output strings are also a number, ten digits long, with each 'digit' in base 62. (Think base64 but without -, /, or = (for padding).) 62 possible values and ten positions gives you a maximum value of 839_299_365_868_340_224, which can be represented in 60 bits.

The input string only takes 28 bits to represent, your output string has 60 bits available, and that leaves 32 bits available for storing a randomly-generated number. If we multiply a 32-bit number by 2^28 (the same as a left-shift by 28: 1 << 28) then the lower 28 bits will be free for the originally input number.

Once we've calculated the 60 bit number, we output it in our base 62 notation for human consumption.

To reverse the process, you decode the base 62 number to get our 60 bit number; split the 60 bit number into the lower 28 bit input number and upper 32 bit random number, and then output the 28 bit number in the original format: three base 26 digits followed by four base 10 digits.

FINAL UPDATE

Yusuf, excellent work converting my Ruby to Java. I'm very impressed, especially given how good your Java version looks: your version is more legible. I'm jealous and impressed. :)

I found the two small bugs that remained in your program: RANDOMMASK was accidentally initialized to 0, because Java doesn't promote all operands into the final data type when executing arithmetic shift statements. Changing 1 to 1L forces the result of 1L << 60 to be a long; without the L, the result of 1 << 60 is an int, and isn't large enough to hold the full number.

Further, the digits weren't being compressed correctly; my Ruby code parsed the characters as an integer, and your Java code interpreted the characters as an integer. (Yours used the character's value; mine converted the character to an integer based on the ascii meaning of the character. Mine wasn't really parsing, since it is just doing a subtraction, but if it were a string, String.toInteger(character) would do the same thing, so it is a lot like parsing.)

But your uncompress logic was correct, and because of the mismatch, the output was incorrect. So I changed your code to parse the digits into integers (and changed from char to int to silence a pointless warning).

Here's a diff of what I had to change in your program to make it work:

--- Compress.java.orig  2011-03-25 16:57:47.000000000 -0700
+++ Compress.java   2011-03-25 17:09:42.000000000 -0700
@@ -1,12 +1,12 @@
-import java.util.*
+import java.util.*;

 public class Compress {

 static char START_A = "A".charAt(0);
 static char START_a = "a".charAt(0);
 static char START_0 = "0".charAt(0);
-static int CODEMASK = ((1 << 28) - 1); //turn on lower 28 bits
-static int RANDOMMASK = ((1 << 60) - 1) & ~ CODEMASK; //turn on upper 32 bits
+static long CODEMASK = ((1 << 28) - 1); //turn on lower 28 bits
+static long RANDOMMASK = ((1L << 60) - 1) & ~ CODEMASK; //turn on upper 32 bits

 public static void main(String[] args) {

@@ -42,10 +42,10 @@
     char a = line.charAt(0);
     char b = line.charAt(1);
     char c = line.charAt(2);
-    char h = line.charAt(3);
-    char i = line.charAt(4);
-    char j = line.charAt(5);
-    char k = line.charAt(6);
+    int h = line.charAt(3) - START_0;
+    int i = line.charAt(4) - START_0;
+    int j = line.charAt(5) - START_0;
+    int k = line.charAt(6) - START_0;

     long small_a = (long) a - START_A;
     long small_b = (long) b - START_A;

And now the full source, just in case that's easier :)

import java.util.*;

public class Compress {

static char START_A = "A".charAt(0);
static char START_a = "a".charAt(0);
static char START_0 = "0".charAt(0);
static long CODEMASK = ((1 << 28) - 1); //turn on lower 28 bits
static long RANDOMMASK = ((1L << 60) - 1) & ~ CODEMASK; //turn on upper 32 bits

public static void main(String[] args) {

    String[] test = new String[]{
            //"AAA0000", "SIN1500", "ABD2123", "SMS3345", "ZZZ9999",
            //"ABD2123", "ABD2123", "ABD2123", "ABD2123", "ABD2123"
            "ABD2123"
            };

    for(String t : test){
        long c = compress(t);
        long a = add_random(c);
        String output = to_output(a);
        long input = from_output(output);

        String[] new_c_r = remove_random(input);
        String u = uncompress(Long.valueOf(new_c_r[0]));

        System.out.println("Original input: " + t);
        System.out.println("    compressed: " + c);
        System.out.println("    after adding random amount: " + a);
        System.out.println("    *output: " + output);
        System.out.println("    *input: " + input);
        System.out.println("    random amount added: " + new_c_r[1]);
        System.out.println("    after removing random amount: " + new_c_r[0]);
        System.out.println("    uncompressed: " + u);
        System.out.println("-----------------------------------------------------------------");
    }

}

public static long compress(String line){ //7 character
    char a = line.charAt(0);
    char b = line.charAt(1);
    char c = line.charAt(2);
    int h = line.charAt(3) - START_0;
    int i = line.charAt(4) - START_0;
    int j = line.charAt(5) - START_0;
    int k = line.charAt(6) - START_0;

    long small_a = (long) a - START_A;
    long small_b = (long) b - START_A;
    long small_c = (long) c - START_A;
    long letters = (small_a * 26 * 26) + (small_b * 26) + small_c;
    long numbers = letters * 10000 + h * 1000 + i*100 + j*10 + k;
    return numbers;
}

public static String uncompress(long number){
    long k = number % 10;
    number /= 10;
    long j = number % 10;
    number /= 10;
    long i = number % 10;
    number /= 10;
    long h = number % 10;
    number /= 10;
    long small_c = number % 26;
    number /= 26;
    long small_b = number % 26;
    number /= 26;
    long small_a = number % 26;
    number /= 26;

    if (number != 0) throw new RuntimeException("input wasn't generated with compress()");

    long a = small_a + START_A;
    long b = small_b + START_A;
    long c = small_c + START_A;

    StringBuffer result = new StringBuffer();
    result.append((char) a).append((char) b).append((char) c).append(h).append(i).append(j).append(k);

    return result.toString();
}

public static long add_random(long number){
    return (((long) (Math.random()* Math.pow(2, 31))) << 28) + number;
}

public static String[] remove_random(long number){
    return new String[]{String.valueOf(number & CODEMASK), String.valueOf(number & RANDOMMASK)};
}

public static String to_output(long number){
    List<Character> a = new ArrayList<Character>();
    do{
        a.add(transform_out(number % 62));
        number /= 62;
    }while(number > 0);

    Collections.reverse(a);

    StringBuffer result = new StringBuffer();
    for(int i=0; i<a.size(); i++){
        Character s = (Character) a.get(i);
        result.append(s);
    }

    return result.toString();
}

public static long from_output(String string){
    long num = 0;
    for(char c : string.toCharArray()){
        num *= 62;
        num += transform_in(c);
    }
    return num;
}

public static char transform_out(long small){
    long out;

    if (small < 0 || small > 61){
        throw new RuntimeException("small should be between 0 and 61, inclusive");
    }
    if(small < 26){
        out = START_A + small;
    }else if(small < 52){
        out = START_a + (small-26);
    }else{
        out = START_0 + (small-52);
    }
    return (char) out;
}


public static long transform_in(char c){
    if(!String.valueOf(c).matches("[a-zA-Z0-9]")){ 
        throw new RuntimeException("char should be A-Z, a-z, or 0-9, inclusive");
    }
    long num = (long) c;

    long out;
    if(num >= START_A && num <= START_A+26) out = num-START_A;
    else if(num >= START_a && num <= START_a+26) out = (num-START_a) + 26;
    else if(num >= START_0 && num <= START_0+10) out = (num-START_0) + 52;
    else throw new RuntimeException("Salah, bego!");

    return out;
}}
🌐
Javapractices
javapractices.com › topic › TopicAction.do
Java Practices->Generating unique IDs
The identifiers generated by UUID are actually universally unique identifiers. ... import java.util.UUID; public class GenerateUUID { public static final void main(String... args){ //generate random UUIDs UUID idOne = UUID.randomUUID(); UUID idTwo = UUID.randomUUID(); log("UUID One: " + idOne); log("UUID Two: " + idTwo); } private static void log(Object object){ System.out.println( String.valueOf(object) ); } } Example run:
🌐
javaspring
javaspring.net › blog › get-random-string-java
Generating Random Strings in Java — javaspring.net
Once we have the character set, we can use random number generators to select characters from this set and build the string. import java.util.Random; public class RandomStringGenerator { private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; private static final Random random = new Random(); public static String generateRandomString(int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { int index = random.nextInt(CHARACTERS.length()); sb.append(CHARACTERS.charAt(index)); } return sb.toString(); } public static void main(String[] args) { int length = 10; String randomString = generateRandomString(length); System.out.println("Random String: " + randomString); } }
🌐
Coderanch
coderanch.com › t › 565034 › java › Create-Unique-Character-String
How to Create a Unique 16 Character String (Java in General forum at Coderanch)
If it must be unique (that is, even the astronomically small chance of duplicates is unacceptable), and it can't be guessable, then your only real options are: 1) Randomly generate 16 characters, and then compare against a list of already generated IDs, and if it's a duplicate, try again.
🌐
javathinking
javathinking.com › blog › how-to-generate-a-random-alpha-numeric-string
How to Generate a Random Alpha-Numeric String in Java: Simple Algorithm for Unique Session/Key Identifiers — javathinking.com
February 23, 2019 - These strings balance readability, compactness, and uniqueness, making them ideal for scenarios where human-readable or space-efficient identifiers are needed. This blog post will guide you through creating a robust, secure, and customizable algorithm to generate random alpha-numeric strings in Java...
🌐
CopyProgramming
copyprogramming.com › howto › auto-generate-unique-random-string-in-spring-mvc-hibernate
Java: Generating Random and Unique Strings in Spring MVC and Hibernate Automatically
February 2, 2024 - Auto generate unique random string in Spring MVC, Usage exampleGENERATED ALWAYS AS IDENTITYFeedback ... efficient word frequency calculator in java auto generate unique random string in spring mvc the apache commons lang library