# Using Math Random in Java

Java, a widely-used programming language, provides a suite of mathematical functions within its standard library, and one of the most commonly utilized among these is Math.random(). It is housed within the java.lang package, Math.random() is designed to generate a pseudo-random double value within the inclusive range of 0.0 and the exclusive upper bound of 1.0. To put it more explicitly, while the resultant number can be 0.0, it will always be a fraction below 1.0, ensuring it never actually reaches that number. The underlying mechanism relies on a pseudo-random number generator, which, while not suitable for high-level cryptographic purposes, serves everyday programming needs proficiently. For tasks requiring random numbers in contexts beyond this default range—such as generating a random integer between two boundaries or selecting a random element from an array—additional arithmetic operations are necessary to manipulate the output of Math.random(). Thus, while the method offers a straightforward way to fetch a random decimal, developers often need to layer on some extra calculations to tailor its results to more specific requirements. In this Java Math Random Example, we created two random numbers for int and double. Click Execute to run the Java Math Random Example online and see the result.
Using Math Random in Java Execute
``````public class RandomNumberDemo {
public static void main(String[] args) {
double randomDouble = Math.random();
System.out.println("Random double: " + randomDouble);

int randomInt = (int) (Math.random() * 100) + 1;
System.out.println("Random integer between 1 and 100: " + randomInt);
}
}
``````
Updated: Viewed: 38 times