Java Program to generate random number.
Objective
Write a Java program to generate random numbers using Math.random() and the Random class.
Algorithm / Approach
- Use
Math.random(), which returns adoublebetween 0.0 and 1.0. - Multiply it by 100 and cast to
intto get a number between 0 and 99. - Alternatively, import
java.util.Random. - Create a
Randomobject and callr.nextInt(100)to get an integer between 0 and 99.
Test.java
import java.util.*;
class Test{
public static void main(String [] ar){
//No. from 0 to 100
//Using Math.random()
int rnum1 = (int)(Math.random()*100);
System.out.println(rnum1);
//No. from 0 to 100
//Using Random class
Random r = new Random();
int rnum2 = r.nextInt(100);
System.out.println(rnum2);
}
}
Expected Output
//execution 1 22 33 //execution 2 11 67
Explanation of the Program
- Java provides two primary ways to generate pseudo-random numbers.
Math.random()is a simple utility that internally uses a single staticjava.util.Randominstance. It is great for quick math scripts.- The
java.util.Randomclass is more robust, allowing you to generate random booleans, floats, and integers with specific upper bounds.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)