java random number between 1 and 10

We have already seen random number generator in java.In this post, we will address specific query on how to generate random number between 1 to 10.

Using random.nextInt() to generate random number between 1 and 10

We can simply use Random class’s nextInt() method to achieve this.

As the documentation says, this method call returns "a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)", so this means if you call nextInt(10), it will generate random numbers from 0 to 9 and that’s the reason you need to add 1 to it.
Here is generic formula to generate random number in the range.

randomGenerator.nextInt((maximum – minimum) + 1) + minimum
In our case,
minimum = 1
maximum = 10so it will be
randomGenerator.nextInt((10 – 1) + 1) + 1
randomGenerator.nextInt(10) + 1

So here is the program to generate random number between 1 and 10 in java.

When you run above program, you will get below output:

==============================
Generating 10 random integer in range of 1 to 10 using Random
==============================
1
9
5
10
2
3
2
5
8
1

Using Math.random() to generate random number between 1 and 10

You can also use Math.random() method to random number between 1 and 10. You can iterate from min to max and use Math.ran
Here is formula for the same:

Let’s see with the help of example:

============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
9
6
5
6
2

Using ThreadLocalRandom.current.nextInt() to generate random number between 1 and 10

If you want to generate random number in current thread, you can use ThreadLocalRandom.current.nextInt() to generate random number between 1 and 10.

ThreadLocalRandom was introducted in JDK 7 for managing multiple threads.

Let’s see with the help of example:

============================
Generating 10 random integer in range of 1 to 10 using Math.random
============================
7
7
4
10
4

That’s all about java random number between 1 and 10.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *