How do I create random number?

The java.lang.Math.random() method returns random number between 0.0 and 1.0 including 0.0 but not including 1.0. By multiplying Math.random() result with a number, for example 10 will give us a range of random number between 0.0 and 10.0.

To get a random number between two numbers (n and m) we can use the formula of: n + (Math.random() * (m - n)). Where n is the lowest number (inclusive) and m is the highest number (exclusive).

package org.kodejava.example.lang;

public class RandomNumberExample {
    public static void main(String[] args) {
        // The Math.random() returns a random number between 0.0 and 1.0 
        // including 0.0 but not including 1.0.
        double number = Math.random();
        System.out.println("Generated number: " + number);

        // By multiplying Math.random() result with a number will give
        // us a range of random number between, for instance 0.0 to 10.0 as
        // shown in the example below.
        number = Math.random() * 10;
        System.out.println("Generated number: " + number);

        // To get a random number between n and m we can use the formula:
        // n + (Math.random() * (m - n)). The example below creates random
        // number between 100.0 and 200.0.
        int n = 100;
        int m = 200;
        number = n + (Math.random() * (m - n));
        System.out.println("Generated number: " + number);

        // Creates an integer random number
        int random = 100 + (int) (Math.random() * 100);
        System.out.println("Generated number: " + random);
    }
}

Here is an example result of our program.

Generated number: 0.670447515721026
Generated number: 5.118459516569203
Generated number: 139.89504952544274
Generated number: 158

Wayan

Programmer, runner, recreational diver, live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. Support me by donating.

1 Comments

Leave a Reply