Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

Java - get random int

0 contributions
14 points

1. ThreadLocalRandom.current().nextInt();

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

Example:

System.out.println(nextInt()); // -852264371
System.out.println(nextInt()); // 191991333
System.out.println(nextInt()); // 32530510
System.out.println(nextInt()); // 1369144098
System.out.println(nextInt()); // 1764071021

2. new Random().nextInt();

public static int nextInt2() {
    return new Random().nextInt();
}

Example:

System.out.println(nextInt2()); // 71226409
System.out.println(nextInt2()); // 2131479325
System.out.println(nextInt2()); // -1467723628
System.out.println(nextInt2()); // 1846156328
System.out.println(nextInt2()); // -1572933873

3. new Random().ints().limit(1).findFirst().getAsInt();

public static int nextInt3() {
    // java 8
    return new Random().ints().limit(1).findFirst().getAsInt();
}

Example:

System.out.println(nextInt3()); // -811935236
System.out.println(nextInt3()); // 1312834066
System.out.println(nextInt3()); // -1462402141
System.out.println(nextInt3()); // 2020063451
System.out.println(nextInt3()); // -966348427


If we want to generate random int in range then it is solved in below post:

https://dirask.com/q/java-generate-random-int-in-range-VjoP81

References:

ThreadLocalRandom.current().nextInt()
new Random().nextInt()
new Random().ints().limit(1).findFirst().getAsInt()

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