How to Generate Random Number in Java?

Generating random numbers in Java is a common task that is often used in a variety of applications, such as games, simulations, and data processing. Fortunately, Java provides several convenient ways to generate random numbers. In this post, we will learn different ways to Generate Random Number in Java.

Using Math.random() method

One way to generate random numbers in Java is to use the Math.random() method. This method returns a random double value between 0 (inclusive) and 1 (exclusive). Here is an example of how to use the Math.random() method to generate a random integer between two values:

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    int min = 10;
    int max = 20;
    int range = max - min + 1;
    int randomNumber = (int)(Math.random() * range) + min;
    System.out.println(randomNumber);
  }
}

Using Random class

Another way to generate random numbers in Java is to use the java.util.Random class. This class provides several methods for generating random numbers of different types, such as nextInt(), nextLong(), and nextDouble(). Here is an example of how to use the java.util.Random class to generate a random integer:

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    Random random = new Random();
    int randomNumber = random.nextInt();
    System.out.println(randomNumber);
  }
}

You can also use the java.util.Random class to generate a random integer within a specific range by using the nextInt(int n) method, which returns a random integer between 0 (inclusive) and n (exclusive). Here is an example of how to use the nextInt(int n) method to generate a random integer between two values:

import java.util.Random;

public class Main {
  public static void main(String[] args) {
    int min = 10;
    int max = 20;
    Random random = new Random();
    int randomNumber = random.nextInt(max - min + 1) + min;
    System.out.println(randomNumber);
  }
}

It’s worth noting that the java.util.Random class is not suitable for all applications that require random numbers. For example, it is not suitable for applications that require a high level of security, such as generating secure passwords or cryptographic keys. In these cases, you should use the java.security.SecureRandom class instead.

That’s it! You now know how to generate random numbers in Java using the Math.random() method and the java.util.Random class. Whether you need to generate random numbers for a game, a simulation, or any other application, these methods will come in handy.