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 :
- Use for generating a one-time access code.
- Use for external Id.
- Complex apex coding.
- Create unique keys in mapping.
- Generate a random number in Apex, you can use the
Math.random()
method. - To generate a random string in Apex, you can use the
Crypto.generateSecureRandom(length)
method. - You can also use the
Crypto.getRandomByte()
method to generate a random byte and then convert it to a string using theEncodingUtil.base64Encode()
method.
Code :
GenerateRandomData.cls:
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 :
What’s your Reaction?
+1
3
+1
1
+1
+1
+1
+1