To generate a 4-digit random number in Java, use ThreadLocalRandom.current().nextInt(1000, 10000) for a number from 1000 to 9999 inclusive, or String.format("%04d", random.nextInt(10000)) if you need leading zeros (like 0042). The first method returns an int; the second returns a String.
Why the Range Matters
A “4-digit number” usually means any integer from 1000 to 9999. If you call nextInt(10000), you get 0–9999, which includes values like 42 or 007 – not what most people expect. To get only true 4-digit numbers, use nextInt(9000) + 1000 or the cleaner nextInt(1000, 10000) (available since Java 8).
If you need a 4-character code that may start with zero (e.g., for an OTP or PIN), you must format the output. String.format("%04d", number) pads with leading zeros, so 42 becomes “0042”.
Using java.util.Random
The classic java.util.Random class works but is thread-safe only with extra synchronization. For most single-threaded programs:
Random rand = new Random();
int number = rand.nextInt(9000) + 1000; // 1000–9999
To get a zero-padded string:
String code = String.format("%04d", rand.nextInt(10000));
Note that Random uses a linear congruential generator (LCG) – it’s fast but not cryptographically secure. For non-security uses like simple games or test data, it’s fine.
Using ThreadLocalRandom (Recommended)
Introduced in Java 7, ThreadLocalRandom is faster in concurrent environments and avoids contention. It’s the go-to for most applications:
int number = ThreadLocalRandom.current().nextInt(1000, 10000);
For a zero-padded string:
String code = String.format("%04d", ThreadLocalRandom.current().nextInt(10000));
This class is static and thread-safe, so you can call it from multiple threads without creating new instances.
Using SecureRandom for Security-Sensitive Codes
If you’re generating OTPs, PINs, or anything that should be unpredictable, use java.security.SecureRandom. It uses a cryptographically strong random number generator (CSPRNG). Example:
SecureRandom secureRandom = new SecureRandom();
int number = secureRandom.nextInt(9000) + 1000;
String code = String.format("%04d", secureRandom.nextInt(10000));
Never use Math.random() for security – it’s not cryptographically secure and also returns a double that you’d have to scale, which is error-prone.
Common Pitfalls and Misconceptions
- Getting a number like 0 or 42: This happens when you use
nextInt(10000)without adding the lower bound. Always specify the range asnextInt(min, max)or usenextInt(max - min) + min. - Forgetting that
nextInt(1000, 10000)excludes 10000: The upper bound is exclusive, so 10000 is never returned. That’s correct because 10000 is 5 digits. - Thinking
Math.random()is fine for OTPs: It’s not secure. UseSecureRandomfor anything that could be guessed. - Assuming
Randomis thread-safe: It is, but with performance costs. UseThreadLocalRandomin multi-threaded code.
Choosing the Right Method
Here’s a quick decision guide:
- Simple non-security integer:
ThreadLocalRandom.current().nextInt(1000, 10000) - Zero-padded code (e.g., “0042”):
String.format("%04d", ThreadLocalRandom.current().nextInt(10000)) - Security-sensitive (OTP, PIN):
SecureRandomwithnextInt(10000)and formatting - Java 6 or older: use
new Random().nextInt(9000) + 1000
Performance and Thread Safety
ThreadLocalRandom is designed for high-concurrency scenarios. Each thread gets its own generator, eliminating contention. In benchmarks, it’s often faster than Random in multi-threaded programs. For single-threaded code, the difference is negligible.
SecureRandom is slower because it gathers entropy from the operating system, but that’s the price of security. For generating a few thousand OTPs, it’s still fast enough.
Frequently Asked Questions
How do I generate a 4-digit number with leading zeros?
Use String.format("%04d", random.nextInt(10000)). This returns a string like “0042” for the number 42. If you need an integer, you can’t have leading zeros – integers don’t store them.
Why does nextInt(10000) sometimes give me 0?
Because 0 is a valid result of nextInt(10000). To get only 1000–9999, use nextInt(1000, 10000) or nextInt(9000) + 1000.
Is Math.random() good enough for random numbers?
For simple non-security uses, yes, but it’s less convenient because it returns a double between 0.0 and 1.0. You’d write (int)(Math.random() * 9000) + 1000. For security, never use it – use SecureRandom.
Can I generate a 4-digit number without using Random?
Yes, you can use System.currentTimeMillis() or nanoTime() and take the last 4 digits, but that’s not truly random and is predictable. Stick to the standard classes.
How do I generate multiple 4-digit numbers in a loop?
Just call the method repeatedly. For example:
for (int i = 0; i < 5; i++) {
int n = ThreadLocalRandom.current().nextInt(1000, 10000);
System.out.println(n);
}
Each call produces an independent random value.
What’s the difference between Random and SecureRandom?
Random is fast but predictable if you know the seed. SecureRandom uses a cryptographically strong algorithm and is suitable for security-sensitive data like passwords or tokens. For a simple 4-digit number, Random is fine unless it’s a security context.
Related
- Data Entry for Registration of Documents: How It Works
- Ctrl+Z Shortcut: What It Does and How to Use It
- Forecast Sheet in Excel: How to Use It
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Excel SUM and Hidden Cells: What Gets Included in Totals?Yes. In Excel for Microsoft 365 on Windows, SUM includes numbers in hidden rows and columns, including rows…
- How to Remove Duplicates in Google Sheets: A Safe GuideTo remove duplicate rows in Google Sheets, select your data, then choose Data > Data cleanup > Remove…
- Link a PivotChart to a Different PivotTable in ExcelYou generally cannot retarget an existing Excel PivotChart directly to a different PivotTable. To make a chart use…
- Proper Excel Table Setup: A Clear Step-by-Step GuideTo set up an Excel table, arrange one record per row and one field per column, give every…
- Excel Zoom Shortcut: How to Zoom In, Out, and Set ScaleIn Excel for Microsoft 365 on Windows, press Alt+W, Q to open the Zoom dialog, enter a percentage…
- HP Shortcut Keys: The Complete List You NeedHP shortcut keys are keyboard combinations that trigger specific actions in Windows or HP-specific software, and the most…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.