How to generate random number using Apex?

Integer len = 5;
String str = string.valueof(Math.abs(Crypto.getRandomLong()));
String randomNumber = str.substring(0, len);
system.debug('Random Number-' + randomNumber);

  • umesh g

    will this create any duplicates as we see through probability

    • yes it can

      • umesh g

        If i don’t want to have duplicates at all but should be just in number of digits like 3 but unique always ?

        • You can check the existing record to identify duplicates or you can write custom logic for it

          • umesh g

            Thanks for your kind responses.

  • fajer ul anum Naqeeb

    how can i receive values in custom field with aid of this code