# Generate random number in java between 1 and 10

posted Sep 13 1 min read

In the programming world, especially while developing some games, we need to generate random numbers. For example, in Ludo (the world-famous dice game) or the cards game, random numbers are generated each time a player rolls the dice. So, it is good to know the logic behind the random numbers. In this article, we are going to see how to generate random numbers with or without range in Java.

# Generating Random Numbers:

Java provides different ways to generate random numbers such as Random class, Math.random() method, or ThreadLocalRandom class. In this post, we will be using the Random class to generate the random numbers. Here is the code that generates 5 random numbers without any range:
``````import java.util.*;      //you can replace this line with import java.util.Random;
public class Main
{
public static void main(String[] args)
{
Random random = new Random();   //creating instance of Random class
for(int i =0; i<5; i++)    //loop to generate 5 numbers
{
int numbers = random.nextInt();   //variable to store random numbers
System.out.println("Random number: " + numbers);   //printing the random number
}
}
}
``````

Output:

``````Random number: -1075417638
Random number: -1101527741
Random number: -585686184
Random number: -114559821
Random number: 658556963
``````

# Generating Random Numbers Within a Range:

To generate a random number within a range, we only need to pass the upper bound as an argument to the nextInt() method. Here is the code that generates 5 random numbers within a given range:

``````import java.util.*;      //you can replace this line with import java.util.Random;
public class Main
{
public static void main(String[] args)
{
Random random = new Random();   //creating instance of Random class
for(int i =0; i<5; i++)    //loop to generate 5 numbers
{
int numbers = random.nextInt(10);   //variable to store random numbers
System.out.println("Random number: " + numbers);   //printing the random number
}
}
}
``````

Output:

``````Random number: 0
Random number: 3
Random number: 7
Random number: 8
Random number: 7
``````

I hope you find this post helpful.