Java - Math random() Method



The Java Math random() returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range. When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression new java.util.Random

This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else. This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

Syntax

public static double random()

Parameters

Here is the detail of parameters −

  • This is a default method and accepts no parameter.

Return Value

  • This method returns a double.

Example 1

In this example, we're showing the usage of Math.random() method to get two random numbers between 0.0 and 1.0. We've created two double variables x and y and initialized them with random values using Math.random() method and then printed their values.

public class Test { 
   public static void main(String args[]) {
      double x = Math.random();
      double y = Math.random();
      System.out.println( x );
      System.out.println( y );
   }
}

This will produce the following result −

Output

0.22036373253931207
0.5886034598551758

Example 2

In this example, we're showing the usage of Math.random() method to get two random numbers between 0.0 and 5.0. We've created two double variables x and y and initialized them with random values using Math.random() method and then multiply them by 5 and then printed their values.

public class Test { 
   public static void main(String args[]) {
      double x = Math.random() * 5.0;
      double y = Math.random() * 5.0;
      System.out.println( x );
      System.out.println( y );
   }
}

This will produce the following result −

Output

0.1825098074241227
4.075268573689158

Example 3

In this example, we're showing the usage of Math.random() method to get two random numbers between 0.0 and -5.0. We've created two double variables x and y and initialized them with random values using Math.random() method and then multiply them by 5 and then printed their values.

public class Test { 
   public static void main(String args[]) {
      double x = Math.random() * -5.0;
      double y = Math.random() * -5.0;
      System.out.println( x );
      System.out.println( y );
   }
}

This will produce the following result −

Output

-0.3173368059581516
-2.5126845240206492

Note − The above results will vary every time you call random() methods.

java_numbers.htm
Advertisements