Monday, January 6, 2025
HomeProgrammingGetting random numbers in Java

Getting random numbers in Java

To generate random numbers in Java, you can use the Random class or Math.random() method.

1. Using Random class:

java
import java.util.Random;

Random rand = new Random();
int randomInt = rand.nextInt(100); // Random integer between 0 and 99
double randomDouble = rand.nextDouble(); // Random double between 0.0 and 1.0

2. Using Math.random():

java
double random = Math.random(); // Random double between 0.0 and 1.0

3. Generating a random integer within a range:

java
int randomInRange = rand.nextInt(50) + 1; // Random integer between 1 and 50
  • Random.nextInt(n) generates an integer between 0 (inclusive) and n (exclusive).
  • Math.random() generates a double between 0.0 and 1.0.
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