How to generate a random string in Apex

aerial view of a beautiful island resort
Reading Time: < 1 minutes

In Salesforce Apex, you can generate a random string using the following code:

private static String generateRandomString(Integer len) {
        final String chars = 'xaxPmno2IDdEwLzbtEvhv6oG1RDT6xQJX3MvF4amaDQ9TUvHgJfdbodlllPTnnuw';
        String randStr = '';
        while (randStr.length() < len) {
            Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
            randStr += chars.substring(idx, idx+1);
        return randStr;

You can call this function by passing in the desired length of the string, like this:

String randomString = generateRandomString(10);

About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.

Related posts

Leave a Reply

%d bloggers like this: