Languages
[Edit]
EN

Java - generate random int in range

7 points
Created by:
Tyreese-Aguirre
379

1. ThreadLocalRandom.current().nextInt(min, max);

public static int nextInt(int min, int max) {
    return ThreadLocalRandom.current().nextInt(min, max);
}

Example:

System.out.println(nextInt(1, 100)); // 51
System.out.println(nextInt(1, 100)); // 98
System.out.println(nextInt(1, 100)); // 17
System.out.println(nextInt(500, 1000)); // 766
System.out.println(nextInt(-100, -5)); // -29

2. new Random().nextInt((max - min) + 1) + min;

public static int nextInt2(int min, int max) {
    return new Random().nextInt((max - min) + 1) + min;
}

Example:

System.out.println(nextInt2(1, 100)); // 60
System.out.println(nextInt2(1, 100)); // 24
System.out.println(nextInt2(1, 100)); // 70
System.out.println(nextInt2(500, 1000)); // 858
System.out.println(nextInt2(-100, -5)); //  -97

3. (int) (Math.random() * ((max - min) + 1)) + min;

public static int nextInt3(int min, int max) {
    return (int) (Math.random() * ((max - min) + 1)) + min;
}

Example:

System.out.println(nextInt3(1, 100)); // 32
System.out.println(nextInt3(1, 100)); // 26
System.out.println(nextInt3(1, 100)); // 99
System.out.println(nextInt3(500, 1000)); // 547
System.out.println(nextInt3(-100, -5)); // -88

4. new Random().ints(min, (max + 1)).limit(1).findFirst().getAsInt();

public static int nextInt4(int min, int max) {
    // java 8
    return new Random().ints(min, (max + 1)).limit(1).findFirst().getAsInt();
}

Example:

System.out.println(nextInt4(1, 100)); // 63
System.out.println(nextInt4(1, 100)); // 72
System.out.println(nextInt4(1, 100)); // 40
System.out.println(nextInt4(500, 1000)); // 893
System.out.println(nextInt4(-100, -5)); // -53

References:

ThreadLocalRandom.nextInt(int origin, int bound) - java docs
Random().nextInt(int bound) - java docs
Math.random() - java docs
Random().ints(int randomNumberOrigin, int randomNumberBound) - java docs

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - random numbers

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join