Java Math random example

Previous
Next

In this post, we will see about Java math random example.
Math’s random method provides you positive signed double value from 0.0 to 1.0.

Syntax

This method can be used in multithreaded environment as it is thread safe.
If you see the source code for random math, you will see that it uses java.util.Random class’s nextDouble() method to generate random number between 0.0 to 1.0.
Source code of Math’s random() method

So you can see from above code, random methods uses java.util.Random class to generate random number.

Example

Let’s say you want to generate random integer from 1 to 10. You can use Math’s random method as below:

Pass maximum as 10 and minimum as 1.You will get random integer between 1 to 10.
Here is the complete example:

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

Math’s random method output
0.6094762145403727 0.984629643759588 0.1391747855327513 0.03367790074630195 0.7327997405792047 0.29391413463517546 0.2757890922600933 0.19606812863092626 0.8941801486372356
Generating random number from 1 to 10
6 8 0 5 8 5 5 0 3

You can use java.util.Random class’s nextInt method also to get random integer values from 0 to 10.

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

Generating random number using Random’s nextInt
9 7 4 3 7 1 7 2 5

random.nextInt(10) method will generate random integer between 0 to 10.
that’s all above Math’s Random method.

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