The Math Random Method in Java

Last updated by Ashwin Ramachandran on Sep 25, 2024 at 11:00 PM
Contents

The math.random() method in Java helps generate pseudorandom numbers, which is very useful while stress-testing solutions against randomly generated values. Often in interviews, we see candidates need to check for corner cases and validate them. Instead of hardcoding values, it’s better to stress test against randomly generated values. Hence this article is dedicated to the math.random() method.

In this article, we’ll discuss:

  • What Is the Math Random Method in Java
  • Math Random Method in Java Example
  • Generate a Random Number in the Range [ left, right ]
  • Generate Random Character Between [ ‘a’, ‘z’ ]
  • Differences Between Math.random() and Random.nextInt() 
  • FAANG Interview Questions on Java Math Random 
  • FAQs on Java Math Random

What Is the Math Random Method in Java?

Math.random() is an in-build method from the java.lang.Math package. It’s useful in returning a pseudorandom double greater than or equal to 0.0 and less than 1.0. These numbers are generated pseudorandomly with (approximately) uniform distribution over the below range:

0.0<=value<1.0, where value is the random number

It first creates an object of the java.util.Random class and then calls the nextDouble() method inside it to return a double. 

So the first time we call the Math.random method, it will internally create a single new pseudorandom-number generator using the java.util.Random class. We use this new pseudorandom-number generator for all calls to this method and nowhere else. 

Also, this method is appropriately synchronized to allow correct usage by more than one thread. That said, if many threads need to generate pseudorandom numbers at a great rate, that may reduce the contention for each thread to have its own pseudo-random-number generator.

Here’s the declaration for java.lang.Math.random() method:

 

public static double random()

 Math Random Method in Java Example

Let’s jump into some code and then try to understand the functionalities of Math.random.

 

 public class Main {

 

    public static void main(String[] args) {

        double value = Math.random();

        System.out.println(“Random Value generated = “+value);

    }

 

}

Output : 

Random Value generated = 0.7201678640927276

In the above program, we use Math.random() to generate a random double and store it in a variable named value. Every time we execute this program, a new random double is printed in the console. The reason is Math.random returns a random double within the range 0.0 (inclusive) and 1.0 (exclusive).

By far now, we have understood the functionality of Math.random. So let’s look at some of the use-cases of it.

Generate Random Number in a Range [ left , right ]

Let’s say we have a range [ left, right ] inclusive. We can use the random() method to generate random numbers between this range. Let’s see how.

public class Main {

 

    public static void main(String[] args) {

        int left = 100;

        int right = 200;

        int randomInteger = getRandomInteger(left , right);

        System.out.println(“Random Integer in [left,right] = “+randomInteger);

    }

 

    private static int getRandomInteger(int left, int right) {

        int range = right – left + 1;

        return (int)(Math.random() * range) + left;

    }

 

}

Output : 

Random Integer in [left,right] = 118

Math.random() returns a double, so we cast it to an integer value.

Here, getRandomInteger method returns an integer within a user-defined range. For our case, the values of left and right equal 100 and 200, respectively. The method returns a random integer in the range [100, 200] inclusive.

Generate Random Character Between [ ‘a’ , ‘z’ ]

We can re-use the functionality of the random() method that allows us to return a value in a range. So we can keep the range as [ 0, 25 ] inclusive since we have 26 characters and then call the method getRandomCharacter( left, right ) to return a random char every time.

public class Main {

     public static void main(String[] args) {

        int left = 0;

        int right = 25;

        char randomCharacter = getRandomCharacter(left , right);

        System.out.println(“Random char in [‘a’,’z’] = “+randomCharacter);

    }

 

    private static char getRandomCharacter(int left, int right) {

        int range = right – left + 1;

        return (char) (((int)( Math.random() * range) + left)+’a’);

    }

 

}

Output : 

Random char in [‘a’,’z’] = i

Now we know ways to generate both random Integers and Characters.

Differences Between Math.random() and Random.nextInt() 

  • Random.nextInt(bound) is both more efficient and less biased than Math.random() * bound. 

Parameter bound is the upper bound (exclusive) and Must be positive.

‍Math.random(): This method uses Random.nextDouble() internally. Random.nextDouble() uses the Random.next() method twice to generate a double that has approximately uniformly distributed bits in its mantissa. Thus it is uniformly distributed in the range 0 to 1-(2^-53).

Random.nextInt(bound) uses Random.next() less than twice on average. It uses Random.next() once, and if the value obtained is above the highest multiple of bound and below Integer MAX_VALUE, the method tries again. Otherwise, it returns the value modulo bound, which prevents the values above the highest multiple of bound below Integer.MAX_VALUE skewing the distribution. Thus, it returns a value that is (approximately) uniformly distributed in the range 0 to bound -1.

  • Random.nextInt() gives regular values when the value of the seed is known. Hence is less advantageous in such cases.

  • Math.random() requires about twice the processing and is subject to synchronization, that is, whether the method is appropriately synchronized to allow correct use by more than one thread. That said, if many threads need to generate pseudo-random-numbers at a great rate, it may reduce the contention for each thread to have its own pseudorandom-number generator.

FAANG Interview Questions on Java Math Random 

  • Generate random strings of length N<=300, consisting of both uppercase and lowercase English alphabets.
  • Print an array composed of random integers each time execution happens.

FAQs on Java Math Random

Question 1: What is the return type of the Math.random() method?

It returns a double in the range 0.0 ( inclusive ) and 1.0 (exclusive)

Question 2: Do Math.random and Random.nextInt() belong to the same java packages?

No. Math.random belongs to java.lang.Math, whereas Random class is present in java.util package

Question 3: To generate random integers, which is better Math.random() or Random.nextInt()?

Random.nextInt() is better in terms of performance.

Are You Ready to Nail Your Next Coding Interview?

Whether you’re a Coding Engineer gunning for Software Developer or Software Engineer roles, or you’re targeting management positions at top companies, IK offers courses specifically designed for your needs to help you with your technical interview preparation!

If you’re looking for guidance and help with getting started, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of Software Engineers to crack the most challenging coding interviews and land jobs at their dream companies, such as Google, Facebook, Apple, Netflix, Amazon, and more!

Sign up now!

————

Article contributed by Problem Setters Official

Last updated on: September 25, 2024
Author
Ashwin Ramachandran
Head of Engineering @ Interview Kickstart. Enjoys cutting through the noise and finding patterns.
Register for our webinar

Uplevel your career with AI/ML/GenAI

Loading_icon
Loading...
1 Enter details
2 Select webinar slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Spring vs Spring Boot

Spring vs Spring Boot: Simplifying Java Application Development

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Reinforcement Learning: Teaching Machines to Make Optimal Decisions

Product Marketing vs Product Management

Product Marketing vs Product Management

Java Scanner reset()

The upper() Function in Python

Insertion Sort Algorithm

Ready to Enroll?

Get your enrollment process started by registering for a Pre-enrollment Webinar with one of our Founders.

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC

Register for our webinar

How to Nail your next Technical Interview

Loading_icon
Loading...
1 Enter details
2 Select slot
By sharing your contact details, you agree to our privacy policy.

Select a Date

Time slots

Time Zone:

Get tech interview-ready to navigate a tough job market

Best suitable for: Software Professionals with 5+ years of exprerience
Register for our FREE Webinar

Next webinar starts in

00
DAYS
:
00
HR
:
00
MINS
:
00
SEC