Thursday, January 16, 2025
HomeProgrammingGetting random numbers in Java

Getting random numbers in Java

In Java, you can generate random numbers using the Random class, Math.random(), or the ThreadLocalRandom class.

  1. Random Class:
    java
    Random random = new Random();
    int randomInt = random.nextInt(100); // Random integer between 0 and 99
  2. Math.random():
    java
    double randomDouble = Math.random(); // Random double between 0.0 and 1.0
    int randomInt = (int) (Math.random() * 100); // Random integer 0-99
  3. ThreadLocalRandom (Recommended for multi-threaded environments):
    java
    int randomInt = ThreadLocalRandom.current().nextInt(100);

These methods allow flexibility in generating random numbers.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x