Languages
[Edit]
EN

Java - generate random string of size n characters

0 points
Created by:
Brett4
435

In this article, we would like to show you how to generate random string of size n characters in Java.

The following example presents how to generate random string of size n=10 using characters taken from ALPHABET constant.

Practical example:

package tmpOperations3;

import java.security.SecureRandom;

public class Example {

    static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
            "abcdefghijklmnopqrstuvwxyz" +
            "0123456789";
    static SecureRandom random = new SecureRandom();

    static String randomString(int len) {
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++)
            sb.append(ALPHABET.charAt(random.nextInt(ALPHABET.length())));
        return sb.toString();
    }

    public static void main(String[] args) {
        int n = 10;
        System.out.println(randomString(n));
    }
}

Example output:

nmAlwCyp75
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String (popular problems)

Java - generate random string of size n characters
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join