0
0
JavaHow-ToBeginner · 3 min read

How to Use Math.random in Java: Simple Guide with Examples

In Java, you can use Math.random() to generate a random double value between 0.0 (inclusive) and 1.0 (exclusive). To get random numbers in a specific range, multiply the result by the range size and cast it to the desired type.
📐

Syntax

The Math.random() method returns a double value that is greater than or equal to 0.0 and less than 1.0.

To generate a random number in a specific range, use this formula:

  • randomValue = Math.random() * (max - min) + min;
  • Here, min is the lower bound (inclusive), and max is the upper bound (exclusive).

Cast the result to int if you want whole numbers.

java
double randomValue = Math.random();
// randomValue is >= 0.0 and < 1.0

// To get a random number between min (inclusive) and max (exclusive):
double randomInRange = Math.random() * (max - min) + min;
💻

Example

This example shows how to generate a random number between 0 and 1, and a random integer between 1 and 10.

java
public class RandomExample {
    public static void main(String[] args) {
        // Random double between 0.0 (inclusive) and 1.0 (exclusive)
        double randomDouble = Math.random();
        System.out.println("Random double: " + randomDouble);

        // Random integer between 1 and 10 (inclusive)
        int min = 1;
        int max = 10;
        int randomInt = (int)(Math.random() * (max - min + 1)) + min;
        System.out.println("Random integer between 1 and 10: " + randomInt);
    }
}
Output
Random double: 0.374829374 Random integer between 1 and 10: 7
⚠️

Common Pitfalls

One common mistake is forgetting to adjust the range correctly, which can cause unexpected results or errors.

For example, using (int)(Math.random() * max) will generate numbers from 0 up to max-1, not including max.

Also, casting before multiplying will always give 0 because Math.random() returns a double less than 1.

java
/* Wrong: casting before multiplying */
int wrong = (int)Math.random() * 10; // always 0

/* Correct: multiply first, then cast */
int correct = (int)(Math.random() * 10); // 0 to 9
📊

Quick Reference

UsageDescriptionExample
Generate random doubleReturns double >= 0.0 and < 1.0Math.random()
Random int 0 to max-1Multiply by max and cast(int)(Math.random() * max)
Random int min to maxMultiply by (max-min+1) and add min(int)(Math.random() * (max - min + 1)) + min

Key Takeaways

Math.random() returns a double between 0.0 (inclusive) and 1.0 (exclusive).
Multiply Math.random() by the range size and add the minimum to get numbers in a range.
Always multiply before casting to int to avoid getting zero.
Use (int)(Math.random() * (max - min + 1)) + min for inclusive integer ranges.
Remember the upper bound is exclusive unless adjusted with +1.