How do I generate random integers within a specific range in Java?
Last Updated :
27 Dec, 2019
Given two numbers Min and Max, the task is to generate a random integer within this specific range in Java.
Examples:
Input: Min = 1, Max = 100
Output: 89
Input: Min = 100, Max = 899
Output: 514
Approach:
import java.util.concurrent.ThreadLocalRandom;
class GFG {
public static int getRandomValue( int Min, int Max)
{
return ThreadLocalRandom
.current()
.nextInt(Min, Max + 1 );
}
public static void main(String[] args)
{
int Min = 1 , Max = 100 ;
System.out.println( "Random value between "
+ Min + " and " + Max + ": "
+ getRandomValue(Min, Max));
}
}
|
Output:
Random value between 1 and 100: 35
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...