$show=/label

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

SHARE:

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 spe...

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.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java program to generate random number using Random.nextInt(), Math.random() and ThreadLocalRandom
Java program to generate random number using Random.nextInt(), Math.random() and ThreadLocalRandom
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzKjmHlDb3iydz_-fF9VWKl1nHccVZ3GdQ4fogB_fT-IGS1ilowkRhs0SVispFdb1N-6Vn1DdukOnJEwe1ou_KRQFRWbg66IL25Knq4dACDJ5QYA3Vd0AShk7A1zsfYCIJ8FGkRaI2NGI/s400/Java+program+to+generate+random+number+using+Random.nextInt%2528%2529%252C+Math.random%2528%2529+and+ThreadLocalRandom.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhzKjmHlDb3iydz_-fF9VWKl1nHccVZ3GdQ4fogB_fT-IGS1ilowkRhs0SVispFdb1N-6Vn1DdukOnJEwe1ou_KRQFRWbg66IL25Knq4dACDJ5QYA3Vd0AShk7A1zsfYCIJ8FGkRaI2NGI/s72-c/Java+program+to+generate+random+number+using+Random.nextInt%2528%2529%252C+Math.random%2528%2529+and+ThreadLocalRandom.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/11/java-program-to-generate-random-number.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/11/java-program-to-generate-random-number.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content