math.random Java with Examples

Last Updated On Thursday 13th Jan 2022

math.random java

math.random() java

The Math.random()Java method generates a pseudo random number between 0.0 and 1.0.It is the most common method used to generate a random number in Java.

math random java

The Java Math.random() method is used to generate a random number, which is a number created with randomness.It returns a random double, which is the data type used to store floating-point values.

	import java.lang.Math;

class Main {
    public static void main(String[] args) {
        double rand = Math.random();
        System.out.println("Random number: " + rand);
    }
}
	
	Random number: 0.7226254724466756
	

As you can see , the above has returned a random number between 0 and 1.

In order to produce a whole number,we can multiply our random number by another number and round it to the nearest whole number.

java math.random

	import java.lang.Math;

class Main {
    public static void main(String[] args) {
        int rand = (int)(Math.random() * 11);
        System.out.println("Random number: " + rand);
    }
}
	
	Random number: 7
	

java math random

In Some Case we wanted to generate a number between 1 and 500.Then need to multiply with the 500.

java math.random example

	import java.lang.Math;

class Main {
    public static void main(String[] args) {
        int rand = (int)(Math.random() * 500);
        System.out.println("Random number: " + rand);
    }
}
	
	Random number: 297
	

Math.random() method is used to generate random numbers. Math.random() generates a number between 0 and 1.