get random number java between range code example
Example 1: java random numbers in specific range
import java.util.Random;
Random rand = new Random();
int random_integer = rand.nextInt(upperbound-lowerbound) + lowerbound;
Example 2: random number in range java
(int)(Math.random() * ((max - min) + 1)) + min
Copy
Example 3: how to get random number in java in range
package com.mkyong.example.test;
import java.util.Random;
public class TestRandom {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(getRandomNumberInRange(5, 10));
}
}
private static int getRandomNumberInRange(int min, int max) {
if (min >= max) {
throw new IllegalArgumentException("max must be greater than min");
}
Random r = new Random();
return r.nextInt((max - min) + 1) + min;
}
}
Example 4: java generate random integer in range
import java.util.concurrent.ThreadLocalRandom;
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);
Example 5: java random usage
import java.util.Random;
Random rndm = new Random();
int mnmbr = 10;
int rndNumber = rndm.nextInt(mnumber) + 1;
System.out.println(rndNumber);
Example 6: java random number generator in range
int rand = ThreadLocalRandom.current().nextInt(x,y);