ADVERTISEMENTS

How to generate random number in java

Java is also known for its use of the object-oriented programming (OOP) paradigm. These days many applications have the feature to generate numbers randomly i.e. OTP. There are several ways to generate a random number.

  • Math.random
  • java.util.Random
  • java.util.concurrent.ThreadLocalRandom

The following example will explain you about all ways of generating random number in java :

Using the Math.random() method: This method returns a random double value between 0.0 and 1.0. To generate a random number within a specific range, you can multiply the result of Math.random() by the size of the range and then add the minimum value of the range.

int min = 1;
int max = 10;
int randomNum = (int)(Math.random() * (max - min + 1)) + min;

 

Using the java.util.Random class: This class provides a variety of methods for generating random numbers. Here's an example of how to use the nextInt() method to generate a random number within a specific range:

int min = 1;
int max = 10;
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;

 

Using java.util.concurrent.ThreadLocalRandom class: This class is introduced in JDK 7, it is a subclass of the Random class and it is used to generate random numbers from multiple threads.

int min = 1;
int max = 10;
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

 

Java is used for developing mobile apps, web applications, games, and other software. It is known for its "write once, run anywhere" (WORA) principle, which means that Java code can be run on any device that has a Java Virtual Machine (JVM) installed. You can learn java from our Java Tutorials and Java Examples

ADVERTISEMENTS