The Math.random()
method returns a pseudorandom number of data type double
. The range of this random number is given by the following limit:
where is the random number.
This method belongs to the java.lang.Math
class, so you need to import this class before implementing this method.
Using the code snippet below we can generate a random number of type double
. Give it a try!
import java.lang.Math; //importing Math class in Javaclass MyClass {public static void main(String args[]){double rand = Math.random(); // generating random numberSystem.out.println("Random Number: " + rand); // Output is different everytime this code is executed}}
Mostly the random()
method is used to generate random numbers between a specific range. Using this method, we define a method named randomWithRange
, that returns an integer with a user-defined range.
int randomWithRange(int min, int max){int range = (max - min) + 1;return (int)(Math.random() * range) + min;}
Since the random()
method produces a double
number, we need to cast it in an integer, just as shown in the example below:
class MyClass {int randomWithRange(int min, int max){ //defining method for a random number generatorint range = (max - min) + 1;return (int)(Math.random() * range) + min;}public static void main( String args[] ) {MyClass obj1=new MyClass(); // creating an object of MyClassint rand=obj1.randomWithRange(1,100); // range is from 1 to 100System.out.println(rand);}}