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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.