Register for our webinar

How to Nail your next Technical Interview

1 hour
Loading...
1
Enter details
2
Select webinar slot
*Invalid Name
*Invalid Name
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
*All webinar slots are in the Asia/Kolkata timezone
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.
close-icon
Iks white logo

You may be missing out on a 66.5% salary hike*

Nick Camilleri

Head of Career Skills Development & Coaching
*Based on past data of successful IK students
Iks white logo
Help us know you better!

How many years of coding experience do you have?

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
Iks white logo

FREE course on 'Sorting Algorithms' by Omkar Deshpande (Stanford PhD, Head of Curriculum, IK)

Thank you! Please check your inbox for the course details.
Oops! Something went wrong while submitting the form.
Our June 2021 cohorts are filling up quickly. Join our free webinar to Uplevel your career
close
closeAbout usWhy usInstructorsReviewsCostFAQContactBlogRegister for Webinar

The Math Random Method in Java

Last updated by Ashwin Ramachandran on Sep 25, 2024 at 11:00 PM | Reading time: 6 minutes

The fast well prepared banner

Attend our Free Webinar on How to Nail Your Next Technical Interview

WEBINAR +LIVE Q&A

How To Nail Your Next Tech Interview

The Math Random Method in Java
Hosted By
Ryan Valles
Founder, Interview Kickstart
strategy
Our tried & tested strategy for cracking interviews
prepare list
How FAANG hiring process works
hiring process
The 4 areas you must prepare for
hiring managers
How you can accelerate your learnings

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: 
November 20, 2024
Author

Ashwin Ramachandran

Head of Engineering @ Interview Kickstart. Enjoys cutting through the noise and finding patterns.

Attend our Free Webinar on How to Nail Your Next Technical Interview

Register for our webinar

How to Nail your next Technical Interview

1
Enter details
2
Select webinar slot
First Name Required*
Last Name Required*
By sharing your contact details, you agree to our privacy policy.
Step 1
Step 2
Congratulations!
You have registered for our webinar
check-mark
Oops! Something went wrong while submitting the form.
1
Enter details
2
Select webinar slot
Step 1
Step 2
check-mark
Confirmed
You are scheduled with Interview Kickstart.
Redirecting...
Oops! Something went wrong while submitting the form.

The Math Random Method in Java

Worried About Failing Tech Interviews?

Attend our webinar on
"How to nail your next tech interview" and learn

Ryan-image
Hosted By
Ryan Valles
Founder, Interview Kickstart
blue tick
Our tried & tested strategy for cracking interviews
blue tick
How FAANG hiring process works
blue tick
The 4 areas you must prepare for
blue tick
How you can accelerate your learnings
Register for Webinar
entroll-image