Home » Java programming language

How to generate random numbers within a range in Java?

In this article, we will learn with an example: how can we print random numbers within a range in java?

Random class

By using Random class, we can generate random numbers using its methods. To use Random class, we need to include java.util.Random package.

In this article, we are using nextInt() method to get/generate integer random numbers from 0 to 999.

Example: In this java program, we are generating 10 integer random numbers from 0 to 999.

import java.util.Random;

public class RandomNumbers
{
	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]);
		}	
	}
}

Output

Random numbers are: 
394
293
373
623
231
502
996
585
899
995

Read more java examples.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.