1.

Generate Random Numbers in Java

Answer»

Java imparts us with three WAYS to generate random NUMBERS. The three ways are:

  • Using the java.util.Random class
  • Using the java.util.Math.random() method
  • Using the java.util.concurrent.ThreadLocalRandom class

The java.util.Random class

We create an object of this class and call predefined methods such as nextInt() and nextDouble() using this object.

Random numbers of several data types can be produced by this method.

Suppose If we pass an argument x to nextInt() then we would get any random integer from 0 to x-1.

For EXAMPLE,

import java.util.Random; public class Example {      public static void main(String args[])    {        Random r= new Random();        int r1 = r.nextInt(20);   // generates random integers from 0 to 19        int r2 = r.nextInt(100); // generates random integers from 0 to 99        System.out.println("The first random number generated is: "+r1);        System.out.println("The second random number generated is "+r2);    } }

The SUBSEQUENT output is as follows:

$javac Example.java $java Example The first random number generated is: 2 The second random number generated is 23

The Math.random() method

The Math.random() is a method of the java.util.Math class. It returns a positive double VALUE between 0.0 (inclusive) and 1.0 (exclusive).

import java.util.*; public class Example {       public static void main(String args[])    {        double x=Math.random();        System.out.println("Random number between 0.0 and 1.0 is "+x);    } }

The random output for the following is as follows:

$javac Example.java $java Example Random number between 0.0 and 1.0 is 0.7534013549366972

The ThreadLocalRandom Class

This is a relatively new feature introduced in JDK 1.7.

The ThreadLocalRandom gives random values for integers, doubles, floats and booleans.

For example,

import java.util.concurrent.ThreadLocalRandom; public class Example {    public static void main(String args[])    {        int intVal = ThreadLocalRandom.current().nextInt();        System.out.println("A random integer : " + intVal);        double doubVal = ThreadLocalRandom.current().nextDouble();        System.out.println("A random double number : "+doubVal);    } }

The output is as follows:

$javac Example.java $java Example A random integer : 1700060375 A random double number : 0.24593329857940383


Discussion

No Comment Found