Generating random numbers in Java is a common task for games, simulations, testing, and security. The simplest way is to use Math.random(), which returns a double between 0.0 (inclusive) and 1.0 (exclusive). For more control—like generating integers within a range or cryptographically secure numbers—use the Random class or SecureRandom. This guide walks you through each method with code examples.
What You’ll Need
- Java Development Kit (JDK) 8 or later installed (most examples work on older versions too).
- A text editor or an IDE like IntelliJ IDEA, Eclipse, or VS Code.
- Basic familiarity with Java syntax (classes, methods, variables).
Step-by-Step
Method 1: Using Math.random()
- Create a new Java class (e.g.,
RandomDemo.java) with amainmethod. - Call
Math.random()to get a randomdoublebetween 0.0 and 1.0:double rand = Math.random(); System.out.println(rand); - Generate an integer in a range (e.g., 1 to 10):
int min = 1; int max = 10; int randomInt = (int)(Math.random() * (max - min + 1)) + min; System.out.println(randomInt);Explanation:
Math.random()gives 0.0 to 0.999…, multiply by 10 gives 0.0 to 9.999…, cast tointtruncates to 0–9, then add 1 to get 1–10.
Method 2: Using the Random Class
- Import the class at the top of your file:
import java.util.Random; - Create an instance of
Random:Random random = new Random(); - Generate different types of random values:
random.nextInt()– any integer (including negative).random.nextInt(bound)– integer from 0 (inclusive) tobound(exclusive).random.nextDouble()– double between 0.0 and 1.0.random.nextBoolean()– true or false.
Example:
int dice = random.nextInt(6) + 1; // 1 to 6 System.out.println(dice); - Generate a random integer in a custom range (e.g., 5 to 15):
int min = 5; int max = 15; int result = random.nextInt(max - min + 1) + min; System.out.println(result);
Method 3: Using SecureRandom for Security-Sensitive Applications
- Import the class:
import java.security.SecureRandom; - Create an instance:
SecureRandom secureRandom = new SecureRandom(); - Use it similarly to Random:
int token = secureRandom.nextInt(1000000); // 0 to 999999 System.out.println(token);Use
SecureRandomfor passwords, tokens, and anything security-related because it uses a cryptographically strong algorithm.
Method 4: Using ThreadLocalRandom (for concurrent code)
- Import the class:
import java.util.concurrent.ThreadLocalRandom; - Generate a random integer in a range directly:
int randomNum = ThreadLocalRandom.current().nextInt(1, 11); // 1 to 10 System.out.println(randomNum);This is faster in multi-threaded environments and is the recommended way for simple random numbers in Java 7+.
Common Mistakes
- Off-by-one errors: Forgetting to add 1 when using
nextInt(bound)orMath.random()to get a range that includes the upper bound. - Using
Randomfor security:Randomis predictable; useSecureRandomfor passwords or tokens. - Creating a new
Randominstance every call: This can produce identical sequences if created in rapid succession. Create one instance and reuse it. - Ignoring the exclusive upper bound:
nextInt(10)returns 0–9, not 1–10.
Tips
- Seed a
Randominstance for reproducible results (e.g., in tests):new Random(42L). - Use
ThreadLocalRandomfor most cases—it’s cleaner and avoids concurrency issues. - Generate a random char from a string:
String chars = "ABC123"; char c = chars.charAt(random.nextInt(chars.length())); - Shuffle a list using
Collections.shuffle(list, random). - For doubles in a range:
min + (max - min) * random.nextDouble().
Troubleshooting
- Getting the same numbers every run: If you use
new Random()without a seed, it should differ; but if you create a new instance every millisecond, it might repeat. Use one instance orThreadLocalRandom. - Compilation errors about
Randomnot found: Make sure you importedjava.util.Random. - Numbers out of expected range: Double-check your formula. For
nextInt(bound), the result is 0 tobound-1. Add an offset correctly. - Security exception when using SecureRandom: On some systems, the default algorithm may be slow or blocked. You can specify an algorithm:
SecureRandom.getInstanceStrong()or usenew SecureRandom()which usually works. - Random numbers not truly random:
Randomuses a linear congruential generator—fine for most purposes, but not for cryptography. Switch toSecureRandom.
Frequently Asked Questions
What is the difference between Math.random() and Random?
Math.random() is a static method that returns a double between 0.0 and 1.0. The Random class provides methods for various types (int, double, boolean) and allows seeding for reproducibility. Use Random for more flexibility.
How do I generate a random number between 1 and 100?
Using Random: random.nextInt(100) + 1. Using Math.random(): (int)(Math.random() * 100) + 1.
Can I generate a random number without importing anything?
Yes, Math.random() is part of java.lang and requires no import. For other classes, you need imports.
Is Random thread-safe?
No, Random is not thread-safe. Use ThreadLocalRandom for concurrent use or synchronize access.
How do I generate a random string?
Combine random integers with a character set. For example, generate a random index into a string of allowed characters and repeat for the desired length.
Why does SecureRandom sometimes throw an exception?
It may fail if the system’s entropy source is unavailable. You can handle it by falling back to new SecureRandom() or specifying a provider.
Related
- How to Add a Row in Excel: 4 Quick Ways
- Software Entry Data Management: How It Works
- Entry Level Data Entry: No Experience Needed?
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- How to Sum Just Subtotals in Excel Without Double-CountingWhen your subtotal rows contain Excel SUBTOTAL formulas, place an outer SUBTOTAL over the detail-and-subtotal range: it skips…
- MS Access Split Form: Put the Datasheet on the BottomYes. In Microsoft Access, set the form’s Split Form Orientation property to Datasheet on Bottom. Open the form…
- Change Google Sheets Date Format to AustraliaTo use Australian dates in Google Sheets, open the spreadsheet in a browser and choose File > Settings.…
- Google Sheets QUERY: How It Works and How to Use ItIn Google Sheets, QUERY uses a SQL-like instruction inside a formula to select, filter, sort, group, and summarize…
- Outlook Reading View: Change the Reading Pane LayoutTo change Outlook’s reading view, adjust the Reading Pane: in classic Outlook for Windows, go to View >…
- How to Change Strikethrough Color in Excel Cells EasilyExcel does not let you set a strikethrough line to a different color from the text. You can…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.