Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

Java - generate random int in range

0 contributions
7 points

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

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more