Languages
[Edit]
EN

Java - get random long

10 points
Created by:
Warren-X
443

1. Generate random long with ThreadLocalRandom

public static long nextLong() {
    return ThreadLocalRandom.current().nextLong();
}

Example:

System.out.println(nextLong()); // 387012672104004517
System.out.println(nextLong()); // 6852957493264943261
System.out.println(nextLong()); // -71063557433901021


2. Generate random long with Random

public static long nextLong2() {
    return new Random().nextLong();
}

Example:

System.out.println(nextLong2()); // 1210711763149946015
System.out.println(nextLong2()); // -7418942686528922245
System.out.println(nextLong2()); // -453231838162786783


3. Generate random long with Random and LongStream

public static long nextLong3() {
    // java 8
    return new Random().longs().limit(1).findFirst().getAsLong();
}

Example:

System.out.println(nextLong3()); // 8162070174534088347
System.out.println(nextLong3()); // 1459269772671493893
System.out.println(nextLong3()); // 433964390590900751


If we want to generate random long in range look into post:
https://dirask.com/q/zjM8wp


References

ThreadLocalRandom - Java docs
Random - Java docs
LongStream - 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