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.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.024974902600698234
Generated number: 2.271051510086771
Generated number: 147.542543014888
Generated number: 112
Latest posts by Wayan (see all)
- How do I add an object to the beginning of Stream? - February 7, 2025
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
Thank you very much! It’s helpful.