1import java.util.Random;
2
3Random rand = new Random();
4
5// Obtain a number between [0 - 49].
6int n = rand.nextInt(50);
7
8// Add 1 to the result to get a number from the required range
9// (i.e., [1 - 50]).
10n += 1;
1import java.util.Random();
2Random <name> = new Random();
3<variable> = <name>.nextInt(<excuslive top limit>);
1// int rand = (int)(Math.random() * range) + min;
2// Java program to demonstrate Math.random() working
3// of java.lang.Math.random() method
4import java.lang.Math;
5
6class Gfg2 {
7
8 // driver code
9 public static void main(String args[])
10 {
11 // define the range
12 int max = 10;
13 int min = 1;
14 int range = max - min + 1;
15
16 // generate random numbers within 1 to 10
17 for (int i = 0; i < 10; i++) {
18 int rand = (int)(Math.random() * range) + min;
19
20 // Output is different everytime this code is executed
21 System.out.println(rand);
22 }
23 }
24}
1// Math.random() returns a random number between 0.0-0.99.
2double rnd = Math.random();
3
4// rnd1 is an integer in the range 0-9 (including 9).
5int rnd1 = (int)(Math.random()*10);
6
7// rnd2 is in the range 1-10 (including 10). The parentheses are necessary!
8int rnd2 = (int)(Math.random()*10) + 1;
9
10// rnd3 is in the range 5-10 (including 10). The range is 10-5+1 = 6.
11int rnd3 = (int)(Math.random()*6) + 5;
12
13// rnd4 is in the range -10 up to 9 (including 9). The range is doubled (9 - -10 + 1 = 20) and the minimum is -10.
14int rnd4 = (int)(Math.random()*20) - 10;
15