Generate Random Number in Java

Java Programs

Summary: In this programming example, we will learn to generate random numbers in Java.

In Java, we can generate random numbers using the following two classes:

  1. Random
  2. Math

Let’s see an example of each of them.

Method 1: Using Random Class

The nextInt(int MAX) method of the Random class (available in java.util package) returns a random integer less than MAX and the nextDouble() method of the same class returns the random floating value between 0 and 1.

Similarly, we can use nextFloat(), nextLong(), nextShort(), etc to generate specific types of a random number in Java.

import java.util.Random;
 
class Main {
  public static void main(String[] args) {
    Random random = new Random();
 
    //Generate random number less than MAX
    //Syntax: random.nextInt(MAX);
    System.out.println("Random Integer less than 10: "+random.nextInt(10));
 
    System.out.println("Random Integer less than 50: "+random.nextInt(50));
 
    //Generate Random number betwenn MIN and MAX
    //Syntax: random.nextInt(MAX-MIN) + MIN;
    System.out.println("Random Integer Between 20 to 30: "+(random.nextInt(30-20) + 20));
 
    
    //Generate Random Float/Double number
    System.out.println("Random Double: "+random.nextDouble());
 
    System.out.println("Random Double less than 20: "+random.nextDouble()*20);
  }
}

Output:

Random Integer less than 10: 8
Random Integer less than 50: 20
Random Integer Between 20 to 30: 25
Random Double: 0.06373045731187232
Random Double less than 20: 9.083174360349421

Method 2: Using Math Class

The static random() method of Math class (available in the java.lang package) can also generate a random number in Java.

Here is the Java program that generates random integers and floating numbers:

class Main {
  public static void main(String[] args) {
   
    //Generate random double
    System.out.println("Random Double: " + Math.random());
 
    //Generate random number less than MAX
    //Syntax:  (int)(Math.random()*MAX);
    System.out.println("Random Integer less than 10: "+ (int)(Math.random()*10));
 
    //Generate random number between MIN and MAX
    //Syntax:  (int)(Math.random()*(MAX-MIN) + MIN);
    System.out.println("Random Integer between 40 and 50: "+ (int)(Math.random() * (50-40) + 40));
 
  }
}

Output:

Random Double: 0.17455668055083073
Random Integer less than 10: 5
Random Integer between 40 and 50: 43

There are the two ways using which we can easily generate random numbers in Java without the need of external library.

Leave a Reply

Your email address will not be published. Required fields are marked *