Java Math random() Method
Last Updated :
20 Dec, 2025
The Math.random() method in Java is used to generate a pseudorandom double value that is greater than or equal to 0.0 and less than 1.0. Internally, this method uses a single instance of java.util.Random to produce random values, making it suitable for basic random number generation tasks. It does not require object creation (static method.
Java
class GFG {
public static void main(String[] args) {
double value = Math.random();
System.out.println(value);
}
}
Explanation: Math.random() generates a decimal value between 0.0 (inclusive) and 1.0 (exclusive). The returned value is stored in value and printed directly.
Syntax of random()
public static double random()
Return Type: "double" a pseudorandom value ≥ 0.0 and < 1.0.
Example 1: Generate a Random Double Value
The Math.random() produces a different decimal value on each execution.
java
class Gfg{
public static void main(String[] args) {
double rand = Math.random();
System.out.println("Random Number: " + rand);
}
}
OutputRandom Number: 0.2338390927184536
Explanation: Math.random() returns a pseudorandom double. Since no seed is manually provided, the value changes on every execution.
Example 2: Generate Random Integers Within a Fixed Range
Now to get random integer numbers from a given fixed range, we take a min and max variable to define the range for our random numbers, both min and max are inclusive in the range.
java
class Gfg{
public static void main(String[] args) {
int min = 1;
int max = 10;
int range = max - min + 1;
for (int i = 0; i < 10; i++) {
int rand = (int)(Math.random() * range) + min;
System.out.println(rand);
}
}
}
Output8
3
10
2
5
4
4
7
5
6
Explanation:
- Math.random() * range scales the random value to the required range size.
- Casting to int removes the decimal part.
- Adding min shifts the value to start from the desired minimum.
To generate random integers in a range: (int)(Math.random() * (max - min + 1)) + min
Note:
- Math.random() is not suitable for cryptographic purposes.
- For better randomness and control, use java.util.Random or SecureRandom.
- The method always returns values less than 1.0, never equal to 1.0.
Explore
Java Basics
OOP & Interfaces
Collections
Exception Handling
Java Advanced
Practice Java