Getting random numbers in Java

To generate random numbers in Java, you can utilize the java.util.Random class or the java.util.concurrent.ThreadLocalRandom class, both of which provide methods for generating random numbers. Here are the steps to generate random numbers in Java:

Using java.util.Random class:

  1. Create an instance of the Random class:
    Random random = new Random();
  2. Generate random integers:
    int randomNumber = random.nextInt();
  3. Generate random doubles:
    double randomDouble = random.nextDouble();
  4. Generate random booleans:
    boolean randomBoolean = random.nextBoolean();
  5. You can also generate random numbers within a specific range:
    int randomNumberInRange = random.nextInt(max - min + 1) + min;
    (where min is the minimum value and max is the maximum value)

Using java.util.concurrent.ThreadLocalRandom class:

  1. Generate random integers:
    int randomNumber = ThreadLocalRandom.current().nextInt();
  2. Generate random doubles:
    double randomDouble = ThreadLocalRandom.current().nextDouble();
  3. Generate random booleans:
    boolean randomBoolean = ThreadLocalRandom.current().nextBoolean();
  4. Generate random numbers within a specific range:
    int randomNumberInRange = ThreadLocalRandom.current().nextInt(min, max + 1);
    (where min is the minimum value and max is the maximum value)
Example
import java.util.concurrent.ThreadLocalRandom; public class TestClass { public static void main(String[] args) { System.out.println(ThreadLocalRandom.current().nextLong(50, 100)); } }

It's important to note that the Random class uses a seed value to generate random numbers, so if you create multiple instances of Random without providing a specific seed, they will produce the same sequence of random numbers. On the other hand, ThreadLocalRandom automatically uses different seed values for different threads, ensuring thread safety in concurrent environments.

Import the required classes

Remember to import the required classes (java.util.Random or java.util.concurrent.ThreadLocalRandom) at the beginning of your Java program.