Java Math random() Method

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.
Transform Your Career
Choose from our industry-leading programs designed for career success
Modern Software and AI Engineering Program
Master full-stack development with AI integration
+1000 moreModern Data Science and ML with specialisation in AI
Advanced data science techniques with AI specialization
+1000 moreAdvanced AIML with Specialisation in Agentic AI
Deep dive into AIML with focus on Agentic systems
+1000 moreDevOps, Cloud & AI Platform Engineering
Build and manage AI-powered cloud infrastructure
+1000 moreAI Engineering Advanced Certification by IIT-Roorkee
Premier AI engineering certification from IIT-Roorkee
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
- The Math.random method in Java provides random numerical values when it is called.
- This, however, will produce double values in the range of 0.0 to 1.0, and not integers.
- However, to obtain integers, you may use implicit or explicit type-casting to obtain values according to your requirements.