Java Math random() Function

random function in java

Java Math Class

Here, in the page we will discuss about the random() Function in java. Java Math class provides several methods to perform several operations on math calculations like max(), min(), sin(), cos(), round(), ceil(), floor(), random function etc.The java.lang.Math class contains various methods for performing basic numeric operations

Java random Function :

Java Collection contains Math class and The class Math contains methods for performing several basic and advance numeric operations such as the exponential, logarithm, square root, and trigonometric functions.
The random() method returns a random positive value that is greater than or equal to 0 and less than 1.
It is a static function of java math class and can be accessed using the math class.

Syntax:

Math.random();

Definition of Parameters:

random method doesn’t takes any argument, it randomly returns the number between 0 and 1.

Return Type :

The random() method returns the random value between 0 and 1 and the returned value is known as pseudo random values which are not truly random values and the values are generated by a definite computational process.

Example :

Run
import java.util.*;

public class Main{
  public static void main(String[] args) {
    // Storing the random value
    double ans = Math.random();
    
    // Printing the random value
    System.out.println("Random Value is : " + ans);
  }
}

Output:

Random Value is : 0.7092569134855187

Explanation:

In the above Example, We are simply storing the random value in a variable of double data type and printing the random value.

Example For Generating Random numbers between some Numbers:

Run
import java.util.*;

public class Main{
  public static void main(String[] args) {
    int high = 5;
    int low = 0;
    
    // accessing the range
    int range = (high - low) + 1;

    // printing the random numbers between 0 and 5
    System.out.print("Random Numbers between 0 and 5 : ");

    for (int i = 0; i < 10; i ++) {
      int randomnumber = (int)(Math.random() * range) + low;
      System.out.print(randomnumber + ", ");
    }
  }
}

Output:

Random Numbers between 0 and 5 : 5, 2, 1, 0, 1, 4, 0, 2, 1, 3

Explanation:

In the above Example, We are printing the random values between 0 and 5 by defining a range.

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription