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;
2
3Random rand = new Random();
4int maxNumber = 10;
5
6int randomNumber = rand.nextInt(maxNumber) + 1;
7
8System.out.println(randomNumber);
1import java.util.Random;
2
3class scratch{
4 public static void main(String[] args) {
5 Random rand = new Random();
6 System.out.println( rand.nextInt(5) );
7 //prints a random Int between 0 - 4 (including 0 & 4);
8 }
9}
1import java.lang.Math;
2
3int randomNumber;
4
5int minimum = 1;
6int maximum = 10 - minimum;
7
8randomNumber = (int)((Math.random()*maximum) + minimum);
9
10System.out.println("Random Number (Between 1-10): " + randomNumber);
1// java.util.random example
2import java.util.Random;
3public class JavaRandomClass
4{
5 public static void main(String[] args)
6 {
7 Random random = new Random();
8 // random integers in range 0 to 999
9 int randInt1 = random.nextInt(1000);
10 int randInt2 = random.nextInt(1000);
11 // printing random integers
12 System.out.println("Random Integers: " + randInt1);
13 System.out.println("Random Integers: " + randInt2);
14 // here we are generating Random doubles
15 double randDou1 = random.nextDouble();
16 double randDou2 = random.nextDouble();
17 // printing random doubles
18 System.out.println("Random Doubles: " + randDou1);
19 System.out.println("Random Doubles: " + randDou2);
20 }
21}
1// Thread safe random number generator.
2
3import java.util.concurrent.ThreadLocalRandom;
4
5
6
7// Generate random integers
8int val = ThreadLocalRandom.current().nextInt();
9
10// Print random int
11System.out.println("Random Integer: " + val);
12