How to generate random numbers using Random class in Java

The Java Random class is a part of the java.util package and contains inbuilt methods to generate random numbers.

The following import statement must be included in your code when using this class.

svg viewer
import java.util.Random;

Built-in Methods

The most frequently used built-in methods for generating random numbers, are the following:

  • nextInt(): Returns a random int value within the range: $ -2,147,483,648<=value<= 2,147,483, 647$

  • nextInt(int range): Returns a random int value within the range: $ 0 <= value < range $

  • nextDouble(): Returns a random double value within the range: $ 0.0 <= value < 1.0 $

  • nextFloat(): Returns a random float value within the range: $ 0.0 <= value < 1.0 $

  • nextLong(): Returns a random long value.

Note: To access the above methods, you need to create an instance of Random class.

Example

The following code generates some random numbers using the Java Random class:

import java.util.Random; //The import statement
class generateRandom {
public static void main( String args[] ) {
//Creating an object of Random class
Random random = new Random();
//Calling the nextInt() method
System.out.println("A random int: " + random.nextInt());
//Calling the overloaded nextInt() method
System.out.println("A random int from 0 to 49: "+ random.nextInt(50));
//Calling the nextDouble() method
System.out.println("A random double: "+ random.nextDouble());
//Calling the nextFloat() method
System.out.println("A random float: "+ random.nextFloat());
//Calling the nextLong() method
System.out.println("A random long: "+ random.nextLong());
}
}
Copyright ©2024 Educative, Inc. All rights reserved