What is Math.random() Method in Java?
0.0 ≤ random < 1.0
Kindly note, that the random number is greater than or equal to 0.0 and less than 1.0.
How to Use Math.random() in Java?
Using the Math.random() method is pretty simple even for beginners.Example 1
Let’s look at a basic example for a clear understanding.
public class RandomTest {
public static void main(String[] args) {
double random1 = Math.random();
double random2 = Math.random();
System.out.println("First Random Number: " + random1);
System.out.println("Second Random Number: " + random2);
}
}
Output
First Random Number: 0.5486939400685561
Second Random Number: 0.23550115674999972
Using random() Method within a Range
Calling Math.random() method looks pretty self-explanatory. However, our need for random numbers doesn’t always lie within the range of 0 and 1. For real-life problems, we can operate within other specified ranges as well. Let’s look at an example of using the Math.random() method for a given range, say 1 to 50.Example 2
public class RandomNumberInRange {
public static int getRandom(int min, int max) {
int range = (max - min) + 1;
int random = (int) ((range * Math.random()) + min);
return random;
}
public static void main(String[] args) {
// Let's play Ludo with 4 Players
int dieRoll = getRandom(1, 6);
System.out.println("Red's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Blue's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Green's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Yellow's Turn: " + dieRoll);
}
}
Output
Red's Turn: 3
Blue's Turn: 2
Green's Turn: 6
Yellow's Turn: 4
GO TO FULL VERSION