Languages
[Edit]
EN

Java - generate random string of size n characters

0 points
Created by:
Brett4
285

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

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