The simplest way to generate a 6-digit random number in Java is int num = 100000 + random.nextInt(900000); using java.util.Random, or int num = 100000 + (int)(Math.random() * 900000); for a quick one-liner. Both produce a number from 100000 to 999999 inclusive, ensuring exactly six digits (no leading zeros).
Why Exactly Six Digits Matters
A common mistake is using random.nextInt(1000000), which returns 0 to 999999—meaning you can get numbers like 42 or 999, which are not six digits. If your application needs a fixed-length code (e.g., OTP, verification code, or order ID), you must shift the range so the minimum is 100000. The formula min + random.nextInt(max - min + 1) works for any range; here min=100000 and max=999999, so the bound is 900000 (since 999999 – 100000 + 1 = 900000).
Using java.util.Random vs Math.random()
java.util.Random is a class that provides methods like nextInt(), nextLong(), and nextDouble(). It uses a linear congruential generator (LCG) which is fast and sufficient for most non-security-critical uses. Math.random() internally uses a Random object, so it’s essentially the same, but nextInt(bound) is more readable and avoids floating-point rounding issues. For a single random number, either works; for many numbers, reuse a single Random instance rather than creating a new one each time—creating a new instance in a loop can produce duplicate sequences if the seeds are close (e.g., when using new Random() with the current time).
Thread-Safe and Secure Alternatives
If your application is multi-threaded, java.util.Random is thread-safe but can have contention. Use ThreadLocalRandom.current().nextInt(100000, 1000000) for better performance in concurrent environments (available since Java 7). For security-sensitive uses like OTPs or password resets, use java.security.SecureRandom, which generates cryptographically strong random numbers. Example: SecureRandom secureRandom = new SecureRandom(); int num = 100000 + secureRandom.nextInt(900000);. SecureRandom is slower but essential when an attacker could guess the number.
Generating with Leading Zeros (e.g., 000123)
Sometimes you need a 6-character string that includes leading zeros, like “001234”. In that case, generate a number from 0 to 999999 and format it with String.format("%06d", num). For example: String code = String.format("%06d", random.nextInt(1000000));. This is common for coupon codes or PINs where “000123” is valid. Be aware that this is not a numeric 6-digit number in the mathematical sense—it’s a string—but it satisfies the visual requirement.
Common Pitfalls and How to Avoid Them
- Off-by-one errors: Using
nextInt(900000)gives 0–899999, so adding 100000 gives 100000–999999. If you usenextInt(1000000)and add 100000, you get 100000–1099999, which can be 7 digits. Always double-check the bound. - Creating a new Random each time: In a loop,
new Random()may use the same seed if created quickly, producing identical numbers. Create one instance outside the loop. - Using
Math.random()with multiplication:(int)(Math.random() * 900000) + 100000is correct, but some write(int)(Math.random() * 1000000)and forget the shift, getting numbers below 100000. - Not handling the range correctly in ThreadLocalRandom: The
nextInt(origin, bound)method takes origin inclusive and bound exclusive, so usenextInt(100000, 1000000)to get 100000–999999.
Performance and Efficiency Tips
For bulk generation (e.g., millions of random numbers), ThreadLocalRandom is typically the fastest because it avoids contention and uses a per-thread seed. SecureRandom is much slower; use it only when needed. If you need a random number that is not predictable (e.g., for a lottery), SecureRandom is the right choice. For simple test data, Random is fine. Also, consider using Random.ints(100000, 1000000).limit(n) to generate a stream of random numbers, which can be collected into a list.
Code Examples for Different Scenarios
Basic single random 6-digit number:Random random = new Random();
int sixDigit = 100000 + random.nextInt(900000);
Using ThreadLocalRandom in a multi-threaded context:int sixDigit = ThreadLocalRandom.current().nextInt(100000, 1000000);
Secure random for OTP:SecureRandom secureRandom = new SecureRandom();
int otp = 100000 + secureRandom.nextInt(900000);
String with leading zeros:String code = String.format("%06d", random.nextInt(1000000));
Stream of 10 random 6-digit numbers:List<Integer> numbers = random.ints(100000, 1000000).limit(10).boxed().collect(Collectors.toList());
Frequently Asked Questions
Q: How do I generate a 6-digit number without leading zeros?
A: Use 100000 + random.nextInt(900000). This ensures the result is between 100000 and 999999, so it always has exactly six digits with no leading zeros.
Q: How do I generate a 6-digit number that can start with zero?
A: Generate a number from 0 to 999999 and format it as a string with leading zeros: String.format("%06d", random.nextInt(1000000)). This gives strings like “000123”.
Q: Is Math.random() or java.util.Random better?
A: They are functionally equivalent, but Random is more flexible and readable. Use ThreadLocalRandom for concurrent code and SecureRandom for security-sensitive uses.
Q: Why does my random number sometimes have 5 digits?
A: Because you likely used random.nextInt(1000000) without adding 100000, so you can get numbers like 42 or 99999. Always shift the range.
Q: Can I use this for a lottery or OTP?
A: For OTPs or any security-sensitive code, use SecureRandom to prevent prediction. For non-critical uses like game dice, Random is sufficient.
Q: How do I generate a 6-digit number in Java 8?
A: Use ThreadLocalRandom.current().nextInt(100000, 1000000) or the older Random class. Java 8 supports both.
Related
- T-SQL Generate Random Number: RAND, NEWID, and More
- Nice Data Entry Software? Top Picks & How to Choose
- Shortcut Keys for Typing: The Essential List
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Uniform Inventory Spreadsheet: Build a Useful TrackerCreate a uniform inventory spreadsheet in Excel with one row per item and size, columns for opening stock,…
- Snowflake LATERAL SPLIT_TO_TABLE: Syntax and ExamplesYes. In Snowflake, use LATERAL SPLIT_TO_TABLE in the FROM clause to turn a delimited string in each source…
- How to Schedule an Email in Outlook Web App for LaterTo schedule an email in Outlook on the web, compose your message, select the arrow beside Send, choose…
- Excel Important Shortcut Keys: A Practical Windows GuideThe most important Excel shortcut keys help you edit, navigate, format, and calculate without repeatedly reaching for the…
- Excel Group of Schools Zimbabwe: Full GuideExcel Group of Schools Zimbabwe is a private Christian school network with campuses in Harare and Bulawayo, offering…
- Google Sheets Cell Dropdown List: Setup and TipsTo create a cell dropdown list in Google Sheets, select the cell or range, choose Insert > Dropdown,…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.