Often we have to generate random numbers during the implementation of a program in Java. There are different ways to do that which is listed below. We can generate a random number in Java by using built-in methods and classes.
Let’s analyze them one by one.
This class is used to generate a stream of pseudo-random numbers and the instances of this particular class are considered as thread safe. In this class we can generate different random data types, i.e. float, int, double.
This class has two constructors (a) Random(), it creates a new random number generator and (b) Random(long seed), which creates random number using a single long seed.
Following program demonstrates random number generation using java.util.Random class.
Output:
This particular method will return a pseudo-random double type value with a positive sign, greater than or equal to 0.0 and less than 1.0. When this method is invoked, it will create a pseudo-random number generator and therefore is called afterward for all the calls towards this method and cannot be used anywhere else.
Let’s have a look at the code which demonstrates random number generation by using Math.Random() method.
Output:
Another example:
Output:
This is a utility class is used to generate random numbers of type int, doubles, boolean, etc. It improves performance and is used for jdk 1.7 and onward.
Below program demonstrate how we use the above class to generate a random number.
Output:
We can simply generate random number between range a range by using Math.Random() and java.util.Random. Let us generate random number between 0 and 10 with the code below.
Output:
In the above code 0 is inclusive and 10 is exclusive. As mentioned previously in the discussion the above code is using Math.Random() method which returns pseudo-random number between the range of 0.0 to 1.0, where later one is exclusive, by multiplying output with and convert into integer, we can generate random integers in any range. If you need random number between any other two numbers e.g. between 0 and 100, just multiply output of random () method with 100 and then cast it into integer result.Conclusion:
Write a comment