How to Generate Random Number in Java

Configurare noua (How To)

Situatie

In Java programming, we often required to generate random numbers while we develop applications. Many applications have the feature to generate numbers randomly, such as to verify the user many applications use the OTP. The best example of random numbers is dice. Because when we throw it, we get a random number between 1 to 6.

In this section, we will learn what is a random number and how to generate random numbers in java

Random numbers are the numbers that use a large set of numbers and selects a number using the mathematical algorithm. It satisfies the following two conditions:

  • The generated values uniformly distributed over a definite interval.
  • It is impossible to guess the future value based on current and past values.
Generating Random Number in Java

In Java, there is three-way to generate random numbers using the method and classes.

  • Using the random() Method
  • Using the Random Class
  • Using the ThreadLocalRandom Class
  • Using the ints() Method (in Java 8)
Using the Math.random() Method

The Java Math class has many methods for different mathematical operations. One of them is the random() method. It is a static method of the Math class. We can invoke it directly. It generates only double type random number greater than or equal to 0.0 and less than 1.0. Before using the random() method, we must import the java.lang.Math class.

Backup

Syntax:

  1. public static double random()

It does not accept any parameter. It returns a pseudorandom double that is greater than or equal to 0.0 and less than 1.0.

Let’s create a program that generates random numbers using the random() method.

Example:

  1. import java.lang.Math;
  2. public class RandomNumberExample1
  3. {
  4. public static void main(String args[])
  5. {
  6. // Generating random numbers
  7. System.out.println(“1st Random Number: “ + Math.random());
  8. System.out.println(“2nd Random Number: “ + Math.random());
  9. System.out.println(“3rd Random Number: “ + Math.random());
  10. System.out.println(“4th Random Number: “ + Math.random());
  11. }
  12. }

Output:

1st Random Number: 0.17434160924512265
2nd Random Number: 0.4297410090709448
3rd Random Number: 0.4828656381344487
4th Random Number: 0.13267917059488898

Solutie

Tip solutie

Permanent

Voteaza

(10 din 20 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?