Often, there’s a need to generate random numbers in Apex. This can be accomplished using the Math.random() function, which produces a positive Double value between 0.0 (inclusive) and 1.0 (exclusive).
However, as this method solely generates numbers within the range of 0.0 and 1.0, it’s crucial to understand how to modify these numbers to suit our specific requirements. Let’s explore some examples demonstrating the creation of various random number variations based on distinct needs.
Obtain A Random Number Between 0 And 10 In Apex
Integer randomNumber = Integer.valueof((Math.random() * 10)); System.debug('randomNumber is'+randomNumber);
Retrieve A Random Number Between 0 And 100 In Apex
Integer randomNumber = Integer.valueof((Math.random() * 100)); System.debug('randomNumber is'+randomNumber);
Retrieve A Random Boolean Value In Apex
Integer randomNumber = Integer.valueof((math.random() * 10)); Boolean randomBoolean = Math.mod(randomNumber,2) == 0 ? true : false; System.debug('randomBoolean is'+randomBoolean);
Retrieve A Random String From A list of Strings In Apex
List<String> availableValues = new List<String>{'Red','Green','Blue','White','Black'}; Integer listSize = availableValues.size() - 1; Integer randomNumber = Integer.valueof((Math.random() * listSize)); String randomString= availableValues[randomNumber]; System.debug('randomString is'+randomString);