This is a very common scenario in programming when there is a requirement to use some random number. This tutorial will help us to generate it in Java. In this post, we will see “how to create a unique random number in Java?”
There are a couple of ways to generate a unique random number, here I am mentioning two ways to do that.
Varied examples to generate a unique random number in Java...!!! Share on X
Note:
If we go by the first way, it works around (0-9) digits to make the unique random number so there is a possibility of re-occurrence of the same number (even the possibility is less as we increase the count of digits that we used to make this number). But, still, conceptually, the probability is always there of repetition of the same number. (but, yes chances are less, so we are good to use it.)
But, if we go by the second way, it works on timestamp basis so it would always be unique. I prefer to use this way.
1st way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | import java.util.Random; public class TestClass { public static void main(String[] args) { System.out.println("Unique ID1 : " + generateRandomNumber(10)); } public static String generateRandomNumber(int maxDigits) { final String digits = "0123456789"; final char[] digitsArray = digits.toCharArray(); Random r = new Random(); StringBuilder number = new StringBuilder(); number.append(digitsArray[r.nextInt(digitsArray.length)]); for (int i = 1; i < maxDigits; i++) { number.append(digitsArray[r.nextInt(digitsArray.length)]); } return number.toString(); } } |
2nd way:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | import java.sql.Timestamp; import java.util.Date; public class TestClass { public static void main(String[] args) { System.out.println("Unique ID2 : " + generatetimeStamp()); } private static String generatetimeStamp() { Date date = new Date(); long time = date.getTime(); Timestamp ts = new Timestamp(time); String tst = ts.toString(); try { tst = tst.substring(0, tst.length() - 4); tst = tst.replace("-", ""); tst = tst.replace(" ", ""); tst = tst.replace(":", ""); } catch (Exception e) { e.printStackTrace(); } returntst; } } |
Varied examples to generate a unique random number in Java...!!! Share on X
If you like this post, please click like button and share it with others on Twitter. Also, check out my other useful blog posts on Java:
Other Useful References: