1. Using new Random().nextInt() method
2. Using Math.random() method
3. Using ThreadLocalRandom.current().nextInt() method
Read Also: How to Shuffle a String in Java
Generate a random number between 1 and 10 in Java
1. Using new Random().nextInt()
We can easily generate a random number between 1(inclusive) and 10(inclusive) in Java using new Random().nextInt() method.
In short,
Random random = new Random();
int randomNumber = min + random.nextInt(max);
where min = 1, max = 10.
Given below is the Java program to generate a random number between 1 and 10 using new Random().nextInt() method.
import java.util.Random;
public class GenerateRandomNumber {
public static void main(String args[]) {
int min = 1;
int max = 10;
System.out.println("Generating random number between 1 and 10 using new Random().nextInt() method");
Random random = new Random();
int randomNum = min + random.nextInt(max);
System.out.println("Generated random number is: " + randomNum);
}
}
Output:
Generating random number between 1 and 10 using new Random().nextInt() method
Generated random number is: 8
2. Using Math.random()
We can also use Math.random() method to generate a random number between 1(inclusive) and 10(inclusive) in Java.
One liner is:
int randomNum = min + (int) (Math.random() * ((max-min) + 1));
where, min = 1 and max = 10.
Given below is the Java program to generate a random number between 1 and 10 using Math.random() method.
public class GenerateRandomNumber2 {
public static void main(String args[]) {
int min = 1;
int max = 10;
System.out.println("Generating random number between 1 and 10 using Math.random() method");
int range = max - min;
int randomNum = min + (int) (Math.random() * (range + 1));
System.out.println("Generated random number is: " + randomNum);
}
}
Output:
Generating random number between 1 and 10 using Math.random() method
Generated random number is: 5
3. Using ThreadLocalRandom.current().nextInt()
We can also use ThreadLocalRandom.current().nextInt() method to generate a random number between 1(exclusive) and 10(inclusive) in Java.
One liner is:
int randomNum = min + ThreadLocalRandom.current().nextInt(min, max);
where, min = 1 and max = 10.
Given below is the Java program to generate a random number between 1 and 10 using ThreadLocalRandom.current().nextInt() method.
import java.util.concurrent.*;
public class GenerateRandomNumber3 {
public static void main(String args[]) {
int min = 1;
int max = 10;
System.out.println("Generating random number between 1 and 10 using ThreadLocalRandom.current.nextInt() method");
int randomNumber = min + ThreadLocalRandom.current().nextInt(min, max);
System.out.println("Generated random number is: " + randomNumber);
}
}
Output:
Generating random number between 1 and 10 using ThreadLocalRandom.current.nextInt() method
Generated random number is: 10
That's all for today. Please mention in the comments if you have any questions related to how to generate a random number between 1 and 10 in Java.