How to use Math.random() method in java?

The Math.random() method in java returns a random value of double type that is greater than or equal to 0.0 and less than 1.0. This method belongs to the java.Lang.Math class, so you need to import this class before implementing​ this method.

The syntax of the random() method is-


The random() method returns a pseudorandom value between 0.0 and 1.0 which means the values returned are not truly random. When you call Math.random() method, values are generated by a definite computational process, that satisfies some condition of randomness. These are called as pseudorandom values.

You can see that the random() method returns different values every time this below code is executed-

 public static void main(String args[]) 
    double rand_value = Math.random();
    System.out.println("Random Number: " + rand_value);  


Random Number: 0.5054125776372458 

If you want values between specific range, you have to multiply the returned value with the magnitude of the range, example-

public static void main(String args[])
        // defining the range
        int upper_bound = 10;
        int lower_bound = 1;
        int range = (upper_bound - lower_bound) + 1;
        // generating random numbers within 1 to 10
        System.out.println("The random numbers between 1 and 10 are: ");
        for (int i = 0; i < 4; i++) {
            // (int) convert double value to int
            int rand_value = (int)(Math.random() * range) + lower_bound;
            // Output is different everytime this code is executed


The random numbers between 1 and 10 are:
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions