Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

random
java
math.random

How to use the Math.random() method 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 Math.random() method returns a pseudorandom number of data type double. The range of this random number is given by the following limit:

0.0x<1.00.0\leq x <1.0
where xx is the random number.

This method belongs to the java.lang.Math class, so you need to import this class before implementing​ this method.

Using the code snippet below we can generate a random number of type double. Give it a try!

import java.lang.Math; //importing Math class in Java
class MyClass {
public static void main(String args[])
{
double rand = Math.random(); // generating random number
System.out.println("Random Number: " + rand); // Output is different everytime this code is executed
}
}
svg viewer

Using random() method for a range

Mostly the random() method is used to generate random numbers between a specific range. Using this method, we define a method named randomWithRange, that returns an integer with a user-defined range.

int randomWithRange(int min, int max){
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}

Since the random() method produces a double number, we need to cast it in an integer, just as shown in the example below:

class MyClass {
int randomWithRange(int min, int max){ //defining method for a random number generator
int range = (max - min) + 1;
return (int)(Math.random() * range) + min;
}
public static void main( String args[] ) {
MyClass obj1=new MyClass(); // creating an object of MyClass
int rand=obj1.randomWithRange(1,100); // range is from 1 to 100
System.out.println(rand);
}
}

RELATED TAGS

random
java
math.random
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