How to create random numbers between given ranges in Java?
How to create random numbers between given ranges in Java?
228
21-Jul-2023
Aryan Kumar
22-Jul-2023There are a few ways to create random numbers between given ranges in Java.
Here's a method using the
Math.random()function:The
Math.random()function returns a random number between 0 and 1. To generate a random number between a specified range, you can multiply the result of theMath.random()function by the difference between the maximum and minimum values, and then add the minimum value.Here's a method using the
Randomclass:The
Randomclass provides a number of methods for generating random numbers. ThenextInt()method generates a random integer between 0 and the specified maximum value. To generate a random number between a specified range, you can pass the difference between the maximum and minimum values to thenextInt()method.Here's a method using the
ThreadLocalRandomclass:The
ThreadLocalRandomclass provides a thread-safe way to generate random numbers. ThenextInt()method generates a random integer between 0 and the specified maximum value. To generate a random number between a specified range, you can pass the difference between the maximum and minimum values to thenextInt()method.Which method you use to create random numbers between given ranges depends on your specific needs. If you are generating random numbers for a single thread, then you can use the
Randomclass. If you are generating random numbers for multiple threads, then you can use theThreadLocalRandomclass.Here are some important things to note about generating random numbers between given ranges:
nextInt()method with the same arguments.