how to generate a random long with 4 digits in java?
This question already has an answer here:
If you want to generate a number from range [0, 9999], you would use random.nextInt(10000)
.
Adding leading zeros is just formatting:
String id = String.format("%04d", random.nextInt(10000));
A Java int
will never have leading 0
(s). You'll need a String
for that. You could use String.format(String, Object...)
or ( PrintStream.printf(String, Object...)
) like
Random rand = new Random();
System.out.printf("%04d%n", rand.nextInt(10000));
The format String
%04d
is for 0 filled 4 digits. And Random.nextInt(int)
will be [0,10000) or [0,9999].