Java Math random() Method

Learn via video course
FREE
View all courses
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Java Course - Mastering the Fundamentals
Java Course - Mastering the Fundamentals
by Tarun Luthra
1000
5
Start Learning
Topics Covered

We frequently need to create random numbers while developing applications in Java programming. Several applications (for instance, a dice roller app) often need to create random numbers. This is where we use Math.random().

The Math.random() in java helps us to generate random double values between 0 and 1.

Syntax

Method Signature:

Syntax:

Here, Math is the class and random() is the method.

Return Type

The function returns only double type random numbers between 0.0 and 1.0, which of course, can be type cast to int, or long.

Java Math random() Method Examples

To understand Math.random in java better, let's look at some examples :

Example : 1

The below example shows how to generate three random numbers using Math.random() method in java. You may use the same to generate more numbers if you want!

Output :

Example : 2

In this example, we will try to generate five random numbers between 15 and 30 :

Output:

Example : 3

In this example, we will initialize an array and use Math.random() to access any 5 elements from the array :

As clearly visible in the output below, we obtain five random numbers from the array provided :

Output:

Conclusion

  1. The Math.random method in Java provides random numerical values when it is called.
  2. This, however, will produce double values in the range of 0.0 to 1.0, and not integers.
  3. However, to obtain integers, you may use implicit or explicit type-casting to obtain values according to your requirements.