In Java programming, you often encounter the requirement to generate random numbers while developing the application. The random() method, which produces random integers, appears to be the most practical approach to creating unexpected in Java. Many apps have a random number generator feature, such as for user verification, and many use OTP codes. The dice are the greatest illustration of a random number. because a number between 1 and 6 will be chosen randomly when we throw it. In this part, we will learn what is a random number and how to generate random numbers in Java.
Random number
A random number is a number that uses a large set of numbers and selects a number using a mathematical algorithm. It meets the following two criteria:
- Over a predetermined time period, the produced values have a uniform distribution.
- Future values cannot be predicted based on previous or present values.
Java Random Number Generation
There are three methods in Java for producing random numbers utilizing methods and classes.
- Making use of the random() Method
- Using the Random Class
- Making use of the ThreadLocalRandom Class
Making use of the random() Method
The Java Math class has many methods for different math operations. The random() function is one of them. It belongs to the Math class’ static method. It just generates a random number of double types greater than or equal to 0.0 and less than 1.0. We need to import the java.lang.Math class before we can use the random() function.
Syntax:
public static double random()
It does not accept any parameter. It returns a pseudorandom double that is greater than or equal to 0.0 and less than 1.0.
Let’s write a program that uses the random() function to produce random integers.
RandomNumberExample1.java
import java.lang.Math; public class RandomNumberExample1 { public static void main(String args[]) { // Generating random numbers System.out.println("1st Random Number: " + Math.random()); System.out.println("2nd Random Number: " + Math.random()); System.out.println("3rd Random Number: " + Math.random()); System.out.println("4th Random Number: " + Math.random()); } }
Output:
1st Random Number: 0.17434160924512265 2nd Random Number: 0.4297410090709448 3rd Random Number: 0.4828656381344487 4th Random Number: 0.13267917059488898
Keep in mind: Every time we run the program, we obtain a different result. Your results might be different from those seen above.
If want to generate random numbers within a certain range, we can also use the below formula.
Math.random() * (max - min + 1) + min
In the above formula, the min value is inclusive while the max value is exclusive.
Let’s program a generator to produce random numbers between 200 and 400.
RandomNumberExample2.java
public class RandomNumberExample2 { public static void main( String args[] ) { int min = 200; int max = 400; //Generate random double value from 200 to 400 System.out.println("Random value of type double between "+min+" to "+max+ ":"); double a = Math.random()*(max-min+1)+min; System.out.println(a); //Generate random int value from 200 to 400 System.out.println("Random value of type int between "+min+" to "+max+ ":"); int b = (int)(Math.random()*(max-min+1)+min); System.out.println(b); } }
Output 1:
Random value of type double between 200 to 400: 233.88329802655377 Random value of type int between 200 to 400: 329
Output 2:
Random value of type double between 200 to 400: 254.8419979875385 Random value of type int between 200 to 400: 284
Using the Random Class
The java.util.Random.ints() method can return an infinite integer stream of randomly generated numbers. All the random numbers will be created inside the range that we choose. We can also specify the stream size so that we get only a limited number of integers.
The following code never ends because we did not provide the ints() function a stream size argument. Only a handful of the output numbers have been displayed.
import java.util.Random; import java.util.stream.IntStream; public class RandomRangeDemo { public static void main(String[] args) { Random r = new Random(); IntStream stream = r.ints(10, 20); stream.forEach(s -> System.out.println(s)); } }
Output:
11 16 16 14 12 13
Generate only 5 random integers by setting the stream size.
import java.util.Random; import java.util.stream.IntStream; public class RandomRangeDemo { public static void main(String[] args) { Random r = new Random(); IntStream stream = r.ints(5, 100, 120); stream.forEach(s -> System.out.println(s)); } }
Output:
103 106 114 117 109
We can use the findFirst() and getAsInt() methods to get only the first random number from the stream.
import java.util.Random; import java.util.stream.IntStream; public class RandomRangeDemo { public static void main(String[] args) { int min = 150, max = 2000;//defining the range Random r = new Random(); IntStream stream = r.ints(1, min, max); int randomNum = stream.findFirst().getAsInt(); System.out.print("The random number is: " + randomNum); } }
Output:
The random number is: 1193
Making use of the ThreadLocalRandom Class
The ThreadLocalRandom class is defined in java.util.concurrent package. It is initialized with an internally generated seed, the same as the random generator of the Math class. It can’t be changed. This class can be applied in the following ways:
ThreadLocalRandom.current().nextX(...)
Where X is Int, Long, etc.
Note: It is impossible to share a ThreadLocalRandom with multiple threads accidentally.
We can generate a random number of any data type, such as integer, float, double, Boolean, long. Follow the instructions below if you plan to use this class to create random numbers:
- First, import the class by using java.util.concurrent.ThreadLocalRandom.
- Call the matching method that you wish to use to create random numbers.
- nextInt()
- nextDouble()
- nextLong()
- nextFloat()
- nextBoolean()
All the above methods override the corresponding method of the Random class and return the corresponding value.
- nextInt(int bound)
- nextDouble(int bound)
- nextLong(int bound)
The above methods parse a parameter bound (upper) that must be positive. It returns a matching randomly generated value between 0 (inclusive) and the specified bound (exclusive). If the bound is negative, IllegalArgumentExcetion will be thrown.
- nextInt(int origin, int bound)
- nextDouble(int origin, int bound)
- nextLong(int origin, int bound)
The above methods parse two parameters origin and bound. The origin specifies the least value returned and the bound specifies the upper bound. It gives back a value created randomly between the bound (exclusive) and the specified origin (inclusive). Additionally, if the origin is greater than or equal to the bound, IllegalArgumentExcetion will be thrown.
Let’s write a program that uses the ThreadLocalRandom class to generate random integers.
RandomNumberExample.java
import java.util.concurrent.ThreadLocalRandom; public class RandomNumberExample4 { public static void main(String args[]) { // Generate random integers between 0 to 999 int a = ThreadLocalRandom.current().nextInt(); int b = ThreadLocalRandom.current().nextInt(); // Print random integer values System.out.println("Randomly Generated Integer Values:"); System.out.println(a); System.out.println(b); // Generate Random double values double c = ThreadLocalRandom.current().nextDouble(); double d = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println("Randomly Generated Double Values:"); System.out.println(c); System.out.println(d); // Generate random boolean values boolean e = ThreadLocalRandom.current().nextBoolean(); boolean f = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println("Randomly Generated Boolean Values:"); System.out.println(e); System.out.println(f); } }
Output 1:
Randomly Generated Integer Values: 348534891 -1887936727 Randomly Generated Double Values: 0.15644440033119833 0.5242730752133399 Randomly Generated Boolean Values: true true
Output 2:
Output 2: Randomly Generated Integer Values: 402755574 295398333 Randomly Generated Double Values: 0.4856461791062565 0.5148677091077654 Randomly Generated Boolean Values: false true
To sum up
In this tutorial, we have implemented our methods using the inbuilt Random() method of the Math class and the nextInt() of the Random class. You can learn different ways to generate a random number within a specified range. Alternatively, you can also directly use the ints() method to generate a stream of random numbers within a given range.
If you have problems with this experience or would like to learn more, please contact ONEXT DIGITAL, and we will assist you. Also, if you are looking for economic growth for your eCommerce business, check out Onext digital. We also offer cost-effective Shopify Development, Mass Commerce Development, and Magento Development services alongside a team of knowledgeable professionals and developers who collaborate directly with designers.
>>Read more
Sorting Algorithms Java: Everything You Need To Know