Java Math.random()

The random() method returns a random value that is greater than or equal to 0.0 and less than 1.0.

Example

class Main {
  public static void main(String[] args) {

// generates a random number between 0 to 1 System.out.println(Math.random());
} } // Output: 0.3034966869965544

Syntax of Math.random()

The syntax of the random() method is:

Math.random()

Note: The random() method is a static method. Hence, we can call the method directly using the class name Math.


random() Parameters

The Math.random() method does not take any parameters.


random() Return Values

  • returns a pseudorandom value between 0.0 and 1.0

Note: The values returned are not truly random. Instead values are generated by a definite computational process that satisfies some condition of randomness. Hence called pseudo random values.


Example 1: Java Math.random()

class Main {
  public static void main(String[] args) {

    // Math.random()
    // first random value
    System.out.println(Math.random());  // 0.45950063688194265

    // second random value
System.out.println(Math.random()); // 0.3388581014886102
// third random value System.out.println(Math.random()); // 0.8002849308960158 } }

In the above example, we can see that the random() method returns three different values.


Example 2: Generate Random Number Between 10 and 20

class Main {
  public static void main(String[] args) {

    int upperBound = 20;
    int lowerBound = 10;

    // upperBound 20 will also be included
    int range = (upperBound - lowerBound) + 1;

    System.out.println("Random Numbers between 10 and 20:");

    for (int i = 0; i < 10; i ++) {

      // generate random number
      // (int) convert double value to int
      // Math.random() generate value between 0.0 and 1.0
int random = (int)(Math.random() * range) + lowerBound;
System.out.print(random + ", "); } } }

Output

Random Numbers between 10 and 20:
15, 13, 11, 17, 20, 11, 17, 20, 14, 14,

Example 3: Access Random Array Elements

class Main {
  public static void main(String[] args) {

    // create an array
    int[] array = {34, 12, 44, 9, 67, 77, 98, 111};

    int lowerBound = 0;
    int upperBound = array.length;

    // array.length will excluded
    int range = upperBound - lowerBound;

    System.out.println("Random Array Elements:");
    // access 5 random array elements
    for (int i = 0; i <= 5; i ++) {

// get random array index int random = (int)(Math.random() * range) + lowerBound;
System.out.print(array[random] + ", "); } } }

Output

Random Array Elements:
67, 34, 77, 34, 12, 77,

Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges