Pages

Tuesday, November 26, 2019

Java program to generate random number using Random.nextInt(), Math.random() and ThreadLocalRandom

1. Overview


In this tutorial, You'll learn how to generate a random number in java. To generate or produce a random number in a specific range, java API has provided several set of classes for this purpose.
We'll be mostly focusing on the following classes and its methods.

.
A) Class Random and method nextInt()
B) Class Math and emthod random()
C) Class ThreadLocalRandom and method nextInt()
.
Java program to generate random number using Random.nextInt(), Math.random() and ThreadLocalRandom



In many scenarios, you might have seen using Math.random() or Random.nextInt() method. The last one is introduced in JDK 1.7 which is for thread-based applications.



2) Creating a random number using Random.nextInt()


Random class is introduced in java 1.0 version as part of java.util package. Random class is used to generate pseudo-random numbers in java. And all instances of Random class are thread-safe.
First, you need to create an instance for Random class to use and next invoke nextInt() method to generate a random number.

Random Java API Reference

First, let us the example program to generate a random integer number.

package com.java.w3schools.blog.java.program.to;

import java.util.Random;

/**
 * 
 * java program to generate a integer random number using random.nextInt().
 * 
 * @author venkateshn
 *
 */
public class GenerateRandomInteger {

 public static void main(String[] args) {

  // creating a Random instance
  Random random1 = new Random();

  // Getting random number 1
  int randomValue1 = random1.nextInt();

  System.out.println("First random value: " + randomValue1);

  // Getting random number 2
  int randomValue2 = random1.nextInt();
  System.out.println("Second random value: " + randomValue2);

  // Getting random number 3
  int randomValue3 = random1.nextInt();
  System.out.println("Third random value: " + randomValue3);
 }

}

Output:

First random value: -448644708
Second random value: 438991708
Third random value: 1521700505

In the above program first created an instance for Random class named random1 and next called three times nextInt() method on random1 instance. So that based on our three-class it has returned three different values. Here we have to note that nextInt() may return a positive or negative value. But if you want to limit the upper limit to certain value then it is possible by providing an int value to the nextInt(int limit) method. Please take a look at the below program that limits the upper bound to 100, 200 and 5000. Whenever you want to generate a random integer number by putting a restriction to upper limit.


// creating a Random instance
Random random1 = new Random();

// Getting random number 1
int randomValue1 = random1.nextInt(100);

System.out.println("First random value with upper limit 100: " + randomValue1);

// Getting random number 2
int randomValue2 = random1.nextInt(200);
System.out.println("Second random value with upper limit 200: " + randomValue2);

// Getting random number 3
int randomValue3 = random1.nextInt(5000);
System.out.println("Third random value with upper limit 5000: " + randomValue3);

Output:

First random value with upper limit 100: 1
Second random value with upper limit 200: 144
Third random value with upper limit 5000: 3936

nextInt(100): Generates a value in range 0 to 100.
nextInt(200): Generates a value in range 0 to 200.
nextInt(5000): Generates a value in range 0 to 5000.

And also Random class has separate methods to generate double, boolean, float, long values and these methods are nextBoolean(), nextDouble(), nextFloat(), nextGaussian() for double and nextLong().

3) Generating a random number using Math.random()


When you've started learning a programming language such as c or java, first you have heard about Math API which has many mathematical utility methods such as min(), max(), ceil(), floor() methods. Math class is part of java.lang package. All methods of Math class are static so you can use them directly with class name example Math.random(). Math has random() method which is to generate a number between 0 and 1. random() method returns a double value so always returned value will have decimal points.

Math Java API Reference

package com.java.w3schools.blog.java.program.to;

/**
 * 
 * java program to generate a random number using Math.random().
 * 
 * @author venkateshn
 *
 */
public class GenerateNumberMath {

 public static void main(String[] args) {

  // genrating a first random double number using Math.random()
  double mathRandomNumber1 = Math.random();
  System.out.println("First number using Math.random() : " + mathRandomNumber1);

  // generating a Second random double number using Math.random()
  double mathRandomNumber2 = Math.random();
  System.out.println("Second number using Math.random() : " + mathRandomNumber1);

  // generating a Third random double number using Math.random()
  double mathRandomNumber3 = Math.random();
  System.out.println("Third number using Math.random() : " + mathRandomNumber3);

 }

}

Output:

First number using Math.random() : 0.4436432940610997
Second number using Math.random() : 0.4436432940610997
Third number using Math.random() : 0.11551578235406579

Output always will be unique because it has a very long decimal point which is a type of double. Many developers do not know that Math.random() internally calls new Random.nextDouble(); method.

4. Generating a random number using ThreadLocalRandom for Multi-Thread applications


ThreadLocalRandom class is added to java in the version of JDK 1.7 as part of the java.util.concurrent package. Before using this concurrent class, first of all why we need this because already a Random class is available. If you use or share a Random instance in a multithreaded enviornment then you may see wrong values and will finally cause poor performance. To maintain its own random values and avoid errors across many threads, class ThreadLocalRandomb is introduced. This class also has similar methods as in Random class.

To create an instance for ThreadLocalRandom class, you must use static method current() from the same class below.

package com.java.w3schools.blog.java.program.to;

import java.util.concurrent.ThreadLocalRandom;

/**
 * 
 * java program to generate a integer random number using random.nextInt().
 * 
 * @author venkateshn
 *
 */
public class GenerateRandomThreadLocalRandom {

 public static void main(String[] args) {

  // creating a Random instance
  ThreadLocalRandom localThreadRandom = ThreadLocalRandom.current();

  // Generating random int values
  int randomTheadLocalValue1 = localThreadRandom.nextInt();
  int randomTheadLocalValue2 = localThreadRandom.nextInt();

  System.out.println("local thread int value 1 : " + randomTheadLocalValue1);
  System.out.println("local thread int value 2 : " + randomTheadLocalValue2);

  // Generating a random double values
  double localThreadDoubleValue1 = ThreadLocalRandom.current().nextDouble();
  double localThreadDoubleValue2 = ThreadLocalRandom.current().nextDouble();

  System.out.println("Local thead double value 1 : " + localThreadDoubleValue1);
  System.out.println("Local thead double value 2 : " + localThreadDoubleValue2);

  // Generating a random long values
  double localThreadLongValue1 = ThreadLocalRandom.current().nextDouble();
  double localThreadLongValue2 = ThreadLocalRandom.current().nextDouble();

  System.out.println("Local thead long value 1 : " + localThreadLongValue1);
  System.out.println("Local thead long value 2 : " + localThreadLongValue2);

  // Generating a random boolean values
  double localThreadBooleanValue1 = ThreadLocalRandom.current().nextDouble();
  double localThreadBooleanValue2 = ThreadLocalRandom.current().nextDouble();

  System.out.println("Local thead boolean value 1 : " + localThreadBooleanValue1);
  System.out.println("Local thead boolean value 2 : " + localThreadBooleanValue2);

 }

}

Output:

local thread int value 1 : -937808768
local thread int value 2 : 208002481
Local thead double value 1 : 0.9926940139462023
Local thead double value 2 : 0.7019886422178186
Local thead long value 1 : 0.7107807282924268
Local thead long value 2 : 0.5335451363741163
Local thead boolean value 1 : 0.8174536377859758
Local thead boolean value 2 : 0.3118478870592345

5. Conclusion


In this article, you have learned to generate a random number in different ways using Random.nextInt(), Math.random() and ThreadLocalRandom.nextInt(). But random() method generates a double value which is between 1 and 0 and this only for positive values. Whereas Random and ThreadLocalRandom work similar way but Random is a good choice when you work in non-threading applications and ThreadLocalRandom is designed for concurrent applications. These two random classes work for both positive and negative values.

No comments:

Post a Comment

Please do not add any spam links in the comments section.