There are many ways to generate random numbers in Java e.g. Math.random() utility function, java.util.Random class or newly introduced ThreadLocalRandom and SecureRandom, added on JDK 1.7. Each has their own pros and cons but if your requirement is simple, you can generate random numbers in Java by using Math.random() method. This method returns a pseudorandom positive double value between 0.0 and 1.0, where 0.0 is inclusive and 1.0 is exclusive. It means Math.random() always return a number greater than or equal to 0.0 and less than 1.0.
Internally it uses java.util.Random class. So when you first call this method, it creates an instance of Random class and caches it for future use. Any further call is a just equivalent of Random.nextDouble().
If your requirement is more sophisticated i.e. you need random numbers between a range or multiple threads needs to generate random numbers simultaneously, then you should look other random solution available in Java.
Since Math.random() method is properly synchronized to ensure the correct value is returned when used by multiple threads, it also becomes a bottleneck when multiple threads simultaneously use it. To solve this problem, JDK 1.7 introduces ThreadLocalRandom class, which allows each thread to keep its own pseudo-random number to reduce contention.
In a scalable environment, ThreadLocalRandom can improve performance significantly as it keeps the instance of a random number generator in a ThreadLocal variable to reduce contention. If security is your concern then you have another option in terms of SecureRandom, which provides a cryptographically strong random number generator.
If you are interested in learning more about ThreadLocalRandom and SecureRandom classes then I suggest reading Java Performance The Definitive Guide By Scott Oaks, he has covered them in good detail in a separate section.
Since Math.random() method is properly synchronized to ensure the correct value is returned when used by multiple threads, it also becomes a bottleneck when multiple threads simultaneously use it. To solve this problem, JDK 1.7 introduces ThreadLocalRandom class, which allows each thread to keep its own pseudo-random number to reduce contention.
In a scalable environment, ThreadLocalRandom can improve performance significantly as it keeps the instance of a random number generator in a ThreadLocal variable to reduce contention. If security is your concern then you have another option in terms of SecureRandom, which provides a cryptographically strong random number generator.
If you are interested in learning more about ThreadLocalRandom and SecureRandom classes then I suggest reading Java Performance The Definitive Guide By Scott Oaks, he has covered them in good detail in a separate section.
How to generate Random numbers between 1 and 10 in Java
If you are using Math.random() function and wondering that it can only return a random number between 0.0 and 1.0, you are wrong. You can still calculate random number between 1 to 10 or between any number by using Math.random() method.In this program, we will learn how to generate a random number between 1 to 100, between 1000 to 9999 or any arbitrary minimum and maximum values. Our method getRandom(int max) returns a random value between 0 and a given number exclusive. Here is the source code :
It's a straightforward code, but the tricky thing is type casting into the int. If you remove the braces between Math.random()*max, you will always end up zero because Java will first cast the double value returned by random() method to int and then multiply it to a max.
Since random() method always returns a value between 0 and 1, casting into an int will always produce a zero. Now if you multiply zero by any other number, you will get zero again. That's why that little bracket is very important.
public static int getRandom(int max){ // return (int) (Math.random()*max); //incorrect always return zero return (int) (Math.random()*max); }
It's a straightforward code, but the tricky thing is type casting into the int. If you remove the braces between Math.random()*max, you will always end up zero because Java will first cast the double value returned by random() method to int and then multiply it to a max.
Since random() method always returns a value between 0 and 1, casting into an int will always produce a zero. Now if you multiply zero by any other number, you will get zero again. That's why that little bracket is very important.
Our next method is getRandomInteger(int maximum, int minimum), which returns a random integer between a given range. Implementation of this method is also self-explanatory.
It also relies on the same logic to multiple random values to a given number to generate another random number in a given range. You can use this code to build a game of dice where you need to generate a random number between 1 and 6.
As I said earlier, If you are interested in learning more about other random number generators in Java e.g. ThreadLocalRandom and SecureRandom classes then I suggest reading Java Performance The Definitive Guide By Scott Oaks. He has provided good comparative analysis and advice on when to use ThreadLocalRandom and SecureRandom classes in Java applications.
You can see that how we can generate random numbers between any range e.g. 0 to 10, 1 to 10, 1 to 100 and 1000 to 9999 by just using Math.random() function, but it also has limitation. You can only generate positive random numbers using this method, if you need a negative random number you should use nextInt(), nextLong() or nextDouble() method of Random class from java.util package, as shown here.
That's all about how to generate random numbers between 0 and 10 in Java. We have also learned how we can calculate random numbers to any arbitrary range by using Math.random() method. Remember its a pseudo-random number.
It also relies on the same logic to multiple random values to a given number to generate another random number in a given range. You can use this code to build a game of dice where you need to generate a random number between 1 and 6.
As I said earlier, If you are interested in learning more about other random number generators in Java e.g. ThreadLocalRandom and SecureRandom classes then I suggest reading Java Performance The Definitive Guide By Scott Oaks. He has provided good comparative analysis and advice on when to use ThreadLocalRandom and SecureRandom classes in Java applications.
Sample Program to generate random numbers in Java
Here is our complete Java program to generate a random number between 0 and 1 as well as 1000 to 9999 or any arbitrary minimum and maximum value./** * Java Program to generate random number between 0 and 1, 1000 and 9999 * and any arbitrary min and max value. * * @author WINDOWS 8 */ public class RandomUtil { public static void main(String a[]){ // Math.random() number return a random double value between // 0 and 1, where 0 is inclusive and 1 is exclusive. System.out.println("Random number between 0 and 1 : " + Math.random()); System.out.println("Random number between 0 and 1 : " + Math.random()); // Now suppose you need random integer between 0 to 10 // you can do following System.out.println("Random integer between 0 and 10 : " + getRandom(10)); System.out.println("Random integer between 0 and 10 : " + getRandom(10)); // Now let's get random number between 1 and 10 System.out.println("Random value between 1 and 10 : " + getRandomInteger(10, 1)); System.out.println("Random value between 1 and 10 : " + getRandomInteger(10, 1)); // Now let's find random number between 1 and 100 System.out.println("Random number between 1 and 100 : " + getRandomInteger(100, 1)); System.out.println("Random number between 1 and 100 : " + getRandomInteger(100, 1)); // generate random number between 1000 and 9999 System.out.println("Random value between 1000 and 9999 : " + getRandomInteger(1000, 10000)); System.out.println("Random value between 1000 and 9999 : " + getRandomInteger(100, 10000)); } /* * Java method to return random integer between 0 and * given number. Pay attention to brackets while casting * (int) Math.random*max will return incorrect result. */ public static int getRandom(int max){ return (int) (Math.random()*max); } /* * returns random integer between minimum and maximum range */ public static int getRandomInteger(int maximum, int minimum){ return ((int) (Math.random()*(maximum - minimum))) + minimum; } } Output Random number between 0 and 1 : 0.04465203527687556 Random number between 0 and 1 : 0.914215990673822 Random integer between 0 and 10 : 9 Random integer between 0 and 10 : 8 Random value between 1 and 10 : 5 Random value between 1 and 10 : 2 Random number between 1 and 100 : 29 Random number between 1 and 100 : 37 Random value between 1000 and 9999 : 3517 Random value between 1000 and 9999 : 3581
That's all about how to generate random numbers between 0 and 10 in Java. We have also learned how we can calculate random numbers to any arbitrary range by using Math.random() method. Remember its a pseudo-random number.
If security concern you should be using SecureRandom class and if concurrency and contention are concern then you should be using ThreadLocalRandom for creating random integers.
If you don't want to write your own method, you can also explore java.util.Random class, which also provides a method for generating random numbers in a given range. If you want to learn more about new concurrent random number generator introduced in Java 7, I suggest to take a look at Java Performance The Definitive Guide By Scott Oaks, he has covered it nicely.
If you don't want to write your own method, you can also explore java.util.Random class, which also provides a method for generating random numbers in a given range. If you want to learn more about new concurrent random number generator introduced in Java 7, I suggest to take a look at Java Performance The Definitive Guide By Scott Oaks, he has covered it nicely.
Now, over to you? What is your favorite way to generate random number in Java? Using java.util.Random class or random method from Math class or anything else?
random.nextInt(10) + 1 is more concise and efficient.
ReplyDeleteIn the first snippet you should probably remove braces in the pink comment, as they make code work properly. ;)
ReplyDeleteIn the second snippet there's "getRandomInteger(100, 10000)" – should be (1000, 10000). But hey, that's nice post anyway. :)
ReplyDelete(double)(10000000 +Math.random()*11111111)
ReplyDelete