Generate Random Number/String in Apex

by Rijwan Mohmmed

Hello friends, today we will discuss Generate Random Number/String in Apex. Apex, the programming language of Salesforce, provides a variety of methods for generating random numbers and strings. These methods can be useful in a variety of situations, such as creating unique IDs, generating passwords, or simulating random events. In this blog post, we will be discussing how to generate random numbers and strings in Apex.

Also, check this :

Key Highlights :

  1. Use for generating a one-time access code.
  2. Use for external Id.
  3. Complex apex coding.
  4. Create unique keys in mapping.
  5. Generate a random number in Apex, you can use the Math.random() method.
  6. To generate a random string in Apex, you can use the Crypto.generateSecureRandom(length) method.
  7. You can also use the Crypto.getRandomByte() method to generate a random byte and then convert it to a string using the EncodingUtil.base64Encode() method.

Code :


public class GenerateRandomData {
    public static String generateRandomNumber(Integer lengthOfNumber) {
        String result = '';
        while(result.length() < lengthOfNumber){
            //Math.abs used to cast Crypto.getRandomLong() to a positive number
            result += String.valueOf(Math.abs(Crypto.getRandomLong()));
        return result.substring(0, lengthOfNumber);
    public static String generateRandomString(Integer lengthOfString) {
        final String chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
        String randStr = '';
        while (randStr.length() < lengthOfString) {
            Integer idx = Math.mod(Math.abs(Crypto.getRandomInteger()), chars.length());
            randStr += chars.substring(idx, idx+1);
        return randStr; 

Output :

Reference :

  1. Apex
What’s your Reaction?

You may also like

Leave a Comment