Home >>Java Programs >How to generate random numbers within a range in Java
In this example, we will see a Java program through which we can generate any random number within a given range.
For generating a random number we will be using the Random class in java. To use the Random class we need to include java.util.Random package.
Program:
import java.util.Random;
public class Main
{
public static void main(String args[])
{
//declaring array to hold 10 random numbers
int[] arr = new int[10];
//object of Random class
Random rand = new Random();
//store value temporary
int value_t;
for(int i = 0; i<10;i=i+1)
{
value_t = rand.nextInt();
value_t = Math.abs(value_t);
value_t = value_t%1000;
arr[i] = value_t;
}
System.out.println("Random numbers are: ");
for(int i = 0; i<10;i=i+1)
{
System.out.println(arr[i]);
}
}
}