Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
random
numbers
class

How to generate random numbers using Random class in Java

Educative Answers Team

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}

RELATED TAGS

java
random
numbers
class
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring