Home Java javaTutorial How to generate random numbers in Java

How to generate random numbers in Java

Jan 17, 2019 am 10:13 AM

How to generate random numbers in Java: first put the import statement before the start of the program class; then create a Random object; and finally select a random number from a certain range.

How to generate random numbers in Java

The operating environment of this article: Windows 7 system, Dell G3 computer, Java version 8.0.

Generating a series of random numbers is one of the common tasks that come up from time to time. In Java, this can be achieved simply using the java.util.Random class.

As with any API class, the first step is to put the import statement before the program class starts:

 import java.util.Random;
Copy after login

Next, create a Random object:

 Random rand = new Random();
Copy after login
Copy after login

Random Object provides you with a simple random number generator. The object's methods provide the ability to select random numbers. For example, the nextInt() and nextLong() methods will return numbers within the range of values ​​(negative and positive numbers) of the int and long data types respectively:

 Random rand = new Random();
for (int j=0;j < 5;j++)
{
  System.out.printf("%12d ",rand.nextInt());
  System.out.print(rand.nextLong());
  System.out.println();
}
Copy after login

The returned number will be a randomly selected int and long value:

-1531072189 -1273932119090680678
1849305478  6088686658983485101
1043154343  6461973185931677018
1457591513  3914920476055359941
-1128970433 -7917790146686928828
Copy after login

Pick random numbers from a range

Typically, the random numbers to be generated need to be from a range (for example, including between 1 and 40). For this purpose, nextInt() method can also accept int parameter. It represents the upper limit of a numeric range. However, the cap number is not included in one of the numbers that can be selected. This may sound confusing, but the nextInt() method works from scratch. For example:

 Random rand = new Random();
rand.nextInt(40);
Copy after login

will only select a random number from 0 to 39. To select from a range starting with 1, just add 1 to the result of the nextInt() method. For example, to select a number between 1 and 40, add to the result a:

 Random rand = new Random();
int pickedNumber = rand.nextInt(40) + 1;
Copy after login

If the range starts with a higher number, you will need:

Subtract the upper number starting number, then add one.

Add the starting number to the result of the nextInt() method.

For example, to choose a number from 5 to 35, the upper limit number would be 35-5 1 = 31, and 5 would need to be added to the result:

 Random rand = new Random();
int pickedNumber = rand.nextInt(31) + 5;
Copy after login

How random is the random class ?

I should point out that the Random class generates random numbers in a deterministic manner. The algorithm that generates randomness is based on a number called a seed. If the seed number is known, it is possible to calculate the number that will result from the algorithm. To prove this, I will use the number of the day Neil Armstrong first set foot on the moon as my seed number (July 20, 1969):

 import java.util.Random;
public class RandomTest {;
  public static void main(String[] args) {
    Random rand = new Random(20071969);
    for (int j = 0; j
Copy after login

No matter who runs this code, the "random" generated The sequence of numbers will be:

 3 0 3 0 7 9 8 2 2 5
Copy after login

By default, the seed number used is given by:

 Random rand = new Random();
Copy after login
Copy after login

is the current time in milliseconds since January 1, 1970. Typically this will produce numbers that are random enough for most purposes. However, please note that two random number generators created within the same millisecond will generate the same random number.

Also be careful when using the Random class for any application that must have a secure random number generator (for example, a gambling program). The seed number can be guessed based on how long the application has been running. Generally, for applications where random numbers are absolutely critical, it's best to find alternatives to Random objects. For most applications that just require some random element (for example, dice for a board game), it works fine.

The above is the detailed content of How to generate random numbers in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles