Home » Java programming language

Java Math Class static double random() with example

Java Math Class static double random() method: Here, we are going to learn about the static double random() method of Math Class with its syntax and example.
Submitted by Preeti Jain, on September 07, 2019

Math Class static double random()

  • This method is available in java.lang package.
  • This method is used to return a random positive double type number, which will be greater than or equal to 0.0 but less than 1.0.
  • This is a static method, so it is accessible with the class name too.
  • In this method, we get random values by the pseudorandom-number generator.
  • This method generates one new pseudorandom-number, which is similar to when we write an expression as, Random r = new Random();
  • This is a synchronized method that means this method is accessible by more than one thread, but one thread at a time.
  • We should go for this method if we generate pseudorandom-number at a huge rate by more than one thread.
  • In this method, we don't pass any parameter.
  • This method does not throw any exception.

Syntax:

    public static double random(){
    }

Parameter(s): void - it does not accpet any parameter.

Return value:

The return type of this method is doube, it returns a value greater than or equal to 0.0 but less than 1.0.

Java program to demonstrate example of random() method

// Java program to demonstrate the example of 
// random() method of Math Class.

public class RandomMethod {
    public static void main(String[] args) {
        // declaring variables & calling method
        double d1 = Math.random();
        double d2 = Math.random();
        double d3 = Math.random();

        // printing values
        System.out.println("d1: " + d1);
        System.out.println("d2: " + d2);
        System.out.println("d3: " + d3);
    }
}

Output

E:\Programs>javac RandomMethod.java

E:\Programs>java RandomMethod
d1: 0.5999311914345431
d2: 0.27793400080453723
d3: 0.38280263956313376



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.