There are many ways to generate a random number in Java. We will explore the following ways:
- Using the Random class
- Using the random() method from Math class
- Using the ThreadLocalRandom class
Generate a Random Number Using the Random class
We can use the Random class from java.util package. Using it we can generate random values of any data type (integer, float, double, Boolean, long). For integers, we can specify the range.
Example:
public class Test { public static void main(String[] args) { // create an object of Random class Random random = new Random(); // Generate random integer 0 to 100 int randomInteger1 = random.nextInt(101); // Generate random integer 0 to 10000 int randomInteger2 = random.nextInt(10001); // Generate random double value double randomDouble = random.nextDouble(); // Generate random long value long randomLong = random.nextLong(); //Generate random boolean value boolean randomBoolean = random.nextBoolean(); System.out.println("randomInteger1: " + randomInteger1); System.out.println("randomInteger2: " + randomInteger2); System.out.println("randomDouble: " + randomDouble); System.out.println("randomLong: " + randomLong); System.out.println("randomBoolean: " + randomBoolean); } }
Generate a random number using the random() method from the Math class
We have one static method random() that belongs to the Math class which we can use to generate random numbers. It generates only double values greater than or equal to 0.0 and less than 1.0.
Example:
public class Test { public static void main(String[] args) { System.out.println(Math.random()); } }
Generate a random number using the ThreadLocalRandom class
There is also the ThreadLocalRandom class from java.util.concurrent package that we can use to generate random values. Like with the Random class, we can generate a random number of any data type, such as integer, float, double, Boolean, long.
Example:
import java.util.concurrent.ThreadLocalRandom; public class Test { public static void main(String[] args) { // Generate random integer value int randomInteger = ThreadLocalRandom.current().nextInt(); // Generate random long value long randomLong = ThreadLocalRandom.current().nextLong(); // Generate random double value double randomDouble = ThreadLocalRandom.current().nextDouble(); //Generate random boolean value boolean randomBoolean = ThreadLocalRandom.current().nextBoolean(); System.out.println("randomInteger: " + randomInteger); System.out.println("randomLong: " + randomLong); System.out.println("randomDouble: " + randomDouble); System.out.println("randomBoolean: " + randomBoolean); } }