java random number between 1 and 10

Previous
Next

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.

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 0 to 10 using Random
==============================
1
9
5
10
2
3
2
5
8
1

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

Previous
Next

Join Our News Letter – Stay Updated

Subscribe to Awesome Java Content.




Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog