Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to generate random number.

Java Code Example — Utility Programs

ADVERTISEMENT

Java Program to generate random number.

Objective

Write a Java program to generate random numbers using Math.random() and the Random class.

Algorithm / Approach

  1. Use Math.random(), which returns a double between 0.0 and 1.0.
  2. Multiply it by 100 and cast to int to get a number between 0 and 99.
  3. Alternatively, import java.util.Random.
  4. Create a Random object and call r.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 static java.util.Random instance. It is great for quick math scripts.
  • The java.util.Random class 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)
ADVERTISEMENT