Generating random numbers in Java


We can generate random numbers using three ways in Java.

  • Using java.util.Random class − Object of Random class can be used to generate random numbers using nextInt(), nextDouble() etc. methods.

  • Using java.lang.Math class − Math.random() methods returns a random double whenever invoked.

  • Using java.util.concurrent.ThreadLocalRandom class − ThreadLocalRandom.current().nextInt() method and similar othjer methods return a random numbers whenever invoked.

Example

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

public class Tester {
   public static void main(String[] args) {

      generateUsingRandom();
      generateUsingMathRandom();
      generateUsingThreadLocalRandom();
   }

   private static void generateUsingRandom() {
      Random random = new Random();
      //print a random int within range of 0 to 10.
      System.out.println(random.nextInt(10));

      //print a random int
      System.out.println(random.nextInt());

      //print a random double
      System.out.println(random.nextDouble());
   }

   private static void generateUsingMathRandom() {
      //print a random double
      System.out.println(Math.random());
   }

   private static void generateUsingThreadLocalRandom() {
      //print a random int within range of 0 to 10.
      System.out.println(ThreadLocalRandom.current().nextInt(10));

      //print a random int
      System.out.println(ThreadLocalRandom.current().nextInt());

      //print a random double
      System.out.println(ThreadLocalRandom.current().nextDouble());

   }
}

Output

9
-1997411886
0.7272728969835154
0.9400193333973254
6
852518482
0.13628495782770622

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 21-Jun-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements