Saturday, September 6, 2025
HomeLanguagesJavaHow do I generate random integers within a specific range in Java?

How do I generate random integers within a specific range in Java?

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:

  • Get the Min and Max which are the specified range.
  • Call the nextInt() method of ThreadLocalRandom class (java.util.concurrent.ThreadLocalRandom) and specify the Min and Max value as the parameter as
    ThreadLocalRandom.current().nextInt(min, max + 1);
  • Return the received random value




// Java program to generate a random integer
// within this specific range
  
import java.util.concurrent.ThreadLocalRandom;
  
class GFG {
  
    public static int getRandomValue(int Min, int Max)
    {
  
        // Get and return the random integer
        // within Min and Max
        return ThreadLocalRandom
            .current()
            .nextInt(Min, Max + 1);
    }
  
    // Driver code
    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
RELATED ARTICLES

Most Popular

Dominic
32270 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6639 POSTS0 COMMENTS
Nicole Veronica
11803 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7029 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS