Java Math random() example

In this guide, you will learn about the Math random() method in Java programming and how to use it with an example.

1. Math random() Method Overview

Definition:

The random() method of Java's Math class is used to generate a double value between 0.0 (inclusive) and 1.0 (exclusive).

Syntax:

Math.random()

Parameters:

This method does not accept any parameters.

Key Points:

- The result will be a double value greater than or equal to 0.0 and less than 1.0.

- The results produced by this method are pseudo-random and are produced using a linear congruential formula.

- To generate random integers or random numbers in a range, additional processing on the returned value is required.

2. Math random() Method Example

public class RandomExample {
    public static void main(String[] args) {
        System.out.println("Random number between 0 and 1: " + Math.random());

        // Generating a random integer between 0 and 100
        int randomInt = (int)(Math.random() * 101);
        System.out.println("Random integer between 0 and 100: " + randomInt);

        // Generating a random double between 5 and 10
        double randomDouble = 5 + (Math.random() * 5);
        System.out.println("Random double between 5 and 10: " + randomDouble);
    }
}

Output:

Random number between 0 and 1: 0.62384940954721
Random integer between 0 and 100: 49
Random double between 5 and 10: 8.11924704773605

(Note: The output will vary every time you run the program since the numbers generated are random.)

Explanation:

In the example:

1. We first demonstrate the direct use of Math.random() to get a random double between 0 and 1.

2. Next, to generate a random integer between 0 and 100, we multiply the result of Math.random() by 101 and cast it to an integer. This ensures the result is within the range [0, 100].

3. Lastly, to generate a random double between 5 and 10, we start the range at 5 and add a random double between 0 and 5.

The Math.random() method is versatile and provides the foundational random capabilities in Java. While it generates numbers between 0 and 1 by default, with some simple arithmetic, you can adjust this range to fit any application's needs.

Related Java Math class method examples

Comments