Generate Random Integers in Java Using Math.random() and Related Concepts
In the realm of programming, randomness plays a crucial role in applications ranging from simple dice games to complex cryptographic systems. However, generating random numbers is not as "random" as it sounds. It requires algorithms that simulate...

public class RandomExample {
public static void main(String[] args) {
double randomValue = Math.random();
System.out.println("Generated Random Value: " + randomValue);
}
}
Generated Random Value: 0.5769421318539201
randomInt = (int)(Math.random() * (max - min + 1)) + min;
public class RandomIntegers {
public static void main(String[] args) {
int min = 1;
int max = 10;
int randomInt = (int)(Math.random() * (max - min + 1)) + min;
System.out.println("Random Integer between 1 and 10: " + randomInt);
}
}
- Math.random() generates a double value between 0.0 and 1.0.
- (Math.random() * (max - min + 1)) scales this value to the desired range.
- + min shifts the range to start from the specified minimum.
import java.util.Arrays;
public class RandomArray {
public static void main(String[] args) {
int min = 5;
int max = 15;
int size = 10;
int[] randomNumbers = new int[size];
for (int i = 0; i < size; i++) {
randomNumbers[i] = (int)(Math.random() * (max - min + 1)) + min;
}
System.out.println("Random Integers: " + Arrays.toString(randomNumbers));
}
}
- A loop generates random numbers within the specified range.
- The results are stored in an array for further processing.
public class DiceRoll {
public static void main(String[] args) {
int diceRoll = (int)(Math.random() * 6) + 1; // Rolling a dice (1-6)
System.out.println("Dice rolled: " + diceRoll);
}
}
Dice rolled: 4
import java.security.SecureRandom;
public class SecureRandomExample {
public static void main(String[] args) {
SecureRandom secureRandom = new SecureRandom();
int randomInt = secureRandom.nextInt(10) + 1; // Between 1 and 10
System.out.println("Secure Random Integer: " + randomInt);
}
}
- Use Math.random() for basic needs like games or simulations.
- Use SecureRandom for sensitive applications like password generation.
Read more at : Generate Random Integers in Java Using Math.random() and Related Concepts
About the author
I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
Comments
Join the discussionNo comments yet. Be the first to comment.





