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
1 2 3 |
public static double random() |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private static Random randomNumberGenerator; private static synchronized void initRNG() { if (randomNumberGenerator == null) randomNumberGenerator = new Random(); } public static double random() { if (randomNumberGenerator == null) initRNG(); return randomNumberGenerator.nextDouble(); } |
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:
1 2 3 4 5 6 |
/* * returns random integer between minimum and maximum range */ public static int getRandomInteger(int minimum, int maximum){ return ((int) (Math.random()*(maximum - minimum))) + minimum; } |
Pass maximum as 10 and minimum as 1.You will get random integer between 1 to 10.
Here is the complete example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package org.arpit.java2blog; public class MathRandomMain { public static void main(String[] args) { System.out.println("Math's random method output"); for (int i = 1; i < 10; i++) { System.out.print(" "+Math.random()); } System.out.println(); System.out.println("Generating random number from 1 to 10"); for (int i = 1; i < 10; i++) { System.out.print(" "+getRandomInteger(1,10)); } } /* * returns random integer between minimum and maximum range */ public static int getRandomInteger(int minimum, int maximum){ return ((int) (Math.random()*(maximum - minimum))) + minimum; } } |
When you run above program, you will get below 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package org.arpit.java2blog; import java.util.Random; public class MathRandomMain { public static void main(String[] args) { System.out.println("Generating random number using Random's nextInt"); Random random=new Random(); for (int i = 1; i < 10; i++) { System.out.print(" "+random.nextInt(10)); } } } |
When you run above program, you will get below output:
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.