Java Program to generate random numbers

Here we are explaining how to write a java program to display random numbers. By using the Random class in java, we can display random numbers.

What is a Random class in java?

The Random class is used to generate random numbers in java. For generating random numbers first we have to create an instance of the Random class. Then by using that instance we can generate the random numbers.

Example:  Random r = new Random();


Here r is the instance of Random class. The random class can generate random numbers of type integer, float, double, etc. Here we are using, nextInt() to generate an integer random number. Here 500 is the limit. So it will generate a random number within 500.

How to implement the java program to generate random numbers?

First, we have to declare the class RandumNumebrs.Create an instance of the java Random class as r. Then using a for loop with three iterations display the integer random numbers within 500 as  System.out.println(r.nextInt(500)).

We can also generate the random numbers within the range of 1000 as System.out.println(r.nextInt(1000)).To generate the random numbers of type double we can use the following code,



STEP 1: Declare the class RandumNumbers with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Create an object of Random class as r.

STEP 4: Display the Random numbers from 1 to 500, using system.out.println().

STEP 5: Set i=1.

STEP 6: By using for loop check i<=3,display r.nextInt(500).

STEP 7: Increment i by one and repeat step 6.


Java Source Code

                                          import java.util.*;
public class RandomNumbers {
   public static void main(String[] args) {    
      Random r = new Random();    
      System.out.println("Random Numbers From 1 to 500:");
      for (int i = 1; i<= 3; i++) {


Random Numbers From 1 to 500: