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.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: Min = 1, Max = 100 Output: 89 Input: Min = 100, Max = 899 Output: 514
- 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
Random value between 1 and 100: 35