Search code examples
javarandomserial-number

Best way to generate unique Random number in Java


I have to generate unique serial numbers for users consisting of 12 to 13 digits. I want to use random number generator in Java giving the system. Time in milliseconds as a seed to it. Please let me know about the best practice for doing so. What I did was like this

Random serialNo = new Random(System.currentTimeMillis());
System.out.println("serial number is "+serialNo);

Output came out as: serial number is java.util.Random@13d8cc98


Solution

  • Create a random number generator using the current time as seed (as you did)

    long seed = System.currentTimeMillis();
    Random rng = new Random​(seed);
    

    Now, to get a number, you have to use the generator, rng is NOT a number.

    long number = rng.nextLong();
    

    According to the documentation, this will give you a pseudorandom number with 281.474.976.710.656 different possible values.

    Now, to get a number with a maximum of 13 digits:

    long number = rng.nextLong() % 10000000000000;
    

    And to get a number with exactly 13 digits:

    long number = (rng.nextLong() % 9000000000000) + 1000000000000;