Generating a random number 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 integers or more control, use the Random class from java.util. This guide covers both methods, plus the modern ThreadLocalRandom and the cryptographically secure SecureRandom.
What You’ll Need
- Java Development Kit (JDK) installed (version 8 or later works for all examples).
- A text editor or IDE (like IntelliJ, Eclipse, or VS Code).
- Basic knowledge of Java syntax and how to run a program.
Step-by-Step
- Use
Math.random()for a quick double.
The simplest method:double r = Math.random();returns a value from 0.0 up to but not including 1.0. To get a number in a range, multiply and add. For example, a random double between 1.0 and 10.0:double r = 1.0 + (Math.random() * 9.0);. - Get a random integer with
Math.random().
Cast tointafter scaling. For a random integer from 1 to 10:int r = (int)(Math.random() * 10) + 1;. The multiplication gives 0.0–9.999…, casting truncates to 0–9, then adding 1 shifts to 1–10. - Use the
Randomclass for more options.
Importjava.util.Random, then create an instance:Random rand = new Random();. Call methods likenextInt(),nextDouble(),nextBoolean(), ornextLong(). For a random integer in a range (0 to bound-1):int r = rand.nextInt(10);gives 0–9. For 1–10, userand.nextInt(10) + 1. - Generate a random integer in a specific range (min to max inclusive).
Userand.nextInt((max - min) + 1) + min. Example: random between 5 and 15:int r = rand.nextInt(11) + 5;because max-min+1 = 11, and adding 5 shifts the range. - Use
ThreadLocalRandomfor concurrency or convenience.
In Java 7+, you can callThreadLocalRandom.current().nextInt(min, max+1)to get a random integer directly in a range. For a double:ThreadLocalRandom.current().nextDouble(min, max). This is thread-safe and often faster thanRandomin multithreaded code. - Use
SecureRandomfor security-sensitive randomness.
For passwords, tokens, or cryptographic keys, useSecureRandomfromjava.security. Instantiate withSecureRandom secureRand = new SecureRandom();and callnextInt(bound)ornextBytes(). This provides a cryptographically strong random number generator. - Put it all together in a complete example.
Write a simple program to test:import java.util.Random; public class RandomExample { public static void main(String[] args) { // Math.random() double d = Math.random(); System.out.println("Double: " + d); // Random class Random rand = new Random(); int r = rand.nextInt(100); // 0-99 System.out.println("Integer: " + r); // Range 1-100 int ranged = rand.nextInt(100) + 1; System.out.println("1-100: " + ranged); } }Compile with
javac RandomExample.javaand run withjava RandomExample. - Seed the
Randomclass if you need reproducible results.
Pass alongseed to the constructor:new Random(42L). The same seed produces the same sequence, useful for testing.Math.random()cannot be seeded directly.
Common Mistakes
- Forgetting to import
java.util.Random. You’ll get a compilation error. Add the import at the top of your file. - Using
nextInt(bound)with a negative bound. ThrowsIllegalArgumentException. Always use positive bounds. - Off-by-one errors in ranges. Remember
nextInt(n)returns 0 to n-1. If you want 1–10, usenextInt(10)+1, notnextInt(11)(that gives 0–10). - Using
Math.random()for integers without casting correctly.(int)Math.random()*10always yields 0 because the cast happens first. Use parentheses:(int)(Math.random()*10). - Using
Randomin multi-threaded code without synchronization.Randomis not thread-safe; useThreadLocalRandominstead. - Using
Math.random()for security. It’s not cryptographically secure. UseSecureRandom.
Tips
- For a random boolean, use
rand.nextBoolean()orThreadLocalRandom.current().nextBoolean(). - To get a random element from an array, use
array[rand.nextInt(array.length)]. - For a random float, use
rand.nextFloat()(returns 0.0–1.0). - If you need many random numbers, create a single
Randominstance and reuse it; creating a new one each time is slower. - Use
Streammethods likerand.ints(5, 1, 100)to generate a stream of 5 random integers between 1 and 99 (inclusive of 1, exclusive of 100). - For reproducible tests, seed your
Randomand log the seed.
Troubleshooting
- Compilation error: “cannot find symbol” for
Random. Addimport java.util.Random;at the top of your file. - Program throws
IllegalArgumentExceptionwhen callingnextInt(0). The bound must be positive. UsenextInt(1)to get 0, or check your logic. - Your random numbers are always the same. If you create a new
Randomwith the same seed each time, you’ll get the same sequence. Remove the seed or use a different seed (e.g.,System.currentTimeMillis()). - Random numbers are not evenly distributed.
Math.random()andRandomare uniformly distributed, but if you’re using modulo, bias can occur. For critical applications, usenextInt(bound)which handles distribution properly. - Getting a negative number from
nextInt(). The no-argnextInt()returns any int, including negative. UsenextInt(bound)to restrict to non-negative.
Frequently Asked Questions
- What is the difference between
Math.random()andRandom?
Math.random()is a static method that returns a double between 0.0 and 1.0. It internally uses aRandomobject. TheRandomclass offers more methods (likenextInt,nextLong) and allows seeding for reproducible sequences. - How do I get a random number between 1 and 100 inclusive?
UseRandom rand = new Random(); int r = rand.nextInt(100) + 1;orThreadLocalRandom.current().nextInt(1, 101)(the upper bound is exclusive). - Can I get a random decimal number between two values?
Yes. For a double between min and max:min + (Math.random() * (max - min)). For example, between 5.5 and 10.5:5.5 + (Math.random() * 5.0). - Is
Randomthread-safe?
No,Randomis not thread-safe. If multiple threads share aRandominstance, use synchronization or, better,ThreadLocalRandomwhich is designed for concurrent use. - How do I generate a random password or token?
UseSecureRandomto generate bytes and encode them (e.g., Base64). For example:byte[] bytes = new byte[16]; new SecureRandom().nextBytes(bytes);then convert to a string. - What is the difference between
RandomandSecureRandom?
Randomuses a linear congruential formula, which is fast but predictable.SecureRandomuses a cryptographically strong algorithm (like SHA1PRNG) that is unpredictable and suitable for security-sensitive tasks.
Related
- Windows Shortcut Keys: The Complete List
- Shortcut for Minimize? Windows & Mac Keys
- Generate 9 Random Numbers: How to Do It
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets IF String Contains: Formulas and ExamplesTo make Google Sheets return one value when a cell contains text and another when it does not,…
- Create Labels in Word 365: A Step-by-Step GuideTo create labels in Word 365, open the Mailings tab, choose Start Mail Merge > Labels, select the…
- Percent of Number in an Excel PivotTable: Show ValuesTo show a PivotTable value as a percentage, right-click a number in the Values area and choose Show…
- How to Insert a Citation in Word OnlineTo insert a citation in Word Online, open the document and check the References tab for Insert Citation.…
- Create a Contact List in Excel: Steps and Best PracticesTo create a contact list in Excel, enter one person per row, add clear column headings such as…
- Currency Exchange in Google Sheets: Rates and FormulasTo get a currency exchange rate in Google Sheets, enter a formula such as =GOOGLEFINANCE("CURRENCY:USDEUR"), which requests the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.