Home  >  Java 8

Java Random

By Arvind Rai, November 29, 2018
This page will walk through Java java.util.Random example. Java Random class generates a stream of pseudorandom numbers. Random class uses 48-bit seed. The instances of Random are threadsafe but the concurrent use of Random has poor performance. We can use ThreadLocalRandom in concurrent environment. The instances of Random are not cryptographically secure. We can use SecureRandom to get cryptographically secure pseudorandom numbers. Math.random() is also used to get pseudorandom numbers in simpler use cases.
Using Java Random we get only pseudorandom numbers and not actual random numbers. Pseudorandom numbers are generated using deterministic process and they appear to be statistically random.

Random

Random is instantiated using constructor
Random() 
Or we can pass seed.
Random(long seed) 
Now we will discuss Random methods.
doubles: Returns stream of pseudorandom double values.
ints: Returns stream of pseudorandom int values.
longs: Returns stream of pseudorandom long values.

The double, int and long methods optionally requires streamSize, randomNumberOrigin and randomNumberBound as arguments.
Now find other methods.
nextBoolean: Returns next pseudorandom Boolean value.
nextBytes: Generates random bytes.
nextDouble: Returns next pseudorandom double value between 0.0 and 1.0.
nextFloat: Returns next pseudorandom float value between 0.0 and 1.0.
nextGaussian: Returns next pseudorandom, Gaussian distributed double value with mean 0.0 and standard deviation 1.0.
nextInt: Returns next pseudorandom int value.
nextLong: Returns next pseudorandom long value.
setSeed: Sets the seed of random number generator.

Example-1: Find the example to use ints method with streamSize, randomNumberOrigin and randomNumberBound as arguments.
RandomDemoForInt.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.IntStream;

public class RandomDemoForInt {
  private static final List<Integer> VALID_PWD_CHARS = new ArrayList<>();
  static {
	IntStream.rangeClosed('0', '9').forEach(VALID_PWD_CHARS::add); // 0-9
	IntStream.rangeClosed('a', 'z').forEach(VALID_PWD_CHARS::add); // a-z
  }

  public static void main(String[] args) {
	int passwordLength = 8;
	System.out.println("---Generated Password---");
	Random random = new Random();
	for (int i = 0; i < 5; i++) {
	  random.ints(passwordLength, 0, VALID_PWD_CHARS.size()).map(VALID_PWD_CHARS::get)
		  .forEach(s -> System.out.print((char) s));
	  System.out.println();
	}
  }
} 
Find the output.
---Generated Password---
qesqftil
oway83fq
abqj04fc
k5mvgymu
gtvlarrt 
Example-2: Find the example of nextBoolean method.
RandomNextBoolean.java
package com.concretepage;
import java.util.Random;

public class RandomNextBoolean {
  public static void main(String[] args) {
	Random random = new Random();
	for(int i = 0; i < 3; i++) {
	   Boolean val = random.nextBoolean();
	   System.out.println(val);
	}
  }
} 
Output
false
false
true 
Example-3: Find the example of nextInt method.
RandomNextInt.java
package com.concretepage;
import java.util.Random;

public class RandomNextInt {
  public static void main(String[] args) {
	Random random = new Random();
	
	//Returns pseudorandom any int value 
	for(int i = 0; i < 3; i++) {
	   int val = random.nextInt();
	   System.out.println(val);
	}
	
	//Returns pseudorandom int with given bound 
	System.out.println("\npseudorandom int within 100");
	for(int i = 0; i < 3; i++) {
	   int val = random.nextInt(100);
	   System.out.println(val);
	}
  }
} 
Output
1354056574
-162483179
1564819453

pseudorandom int within 100
74
29
59 
Example-3: Find the example of nextDouble and nextGaussian methods.
NextDoubleAndNextGaussian.java
package com.concretepage;
import java.util.Random;

public class NextDoubleAndNextGaussian {
  public static void main(String[] args) {
	Random random = new Random();
	
        System.out.println("--- nextDouble ---");
	for(int i = 0; i < 3; i++) {
	   double val = random.nextDouble();
	   System.out.println(val);
	}
	
        System.out.println("--- nextGaussian ---");
	for(int i = 0; i < 3; i++) {
	   double val = random.nextGaussian();
	   System.out.println(val);
	}
  }
} 
Output
--- nextDouble ---
0.649375874922564
0.42725137154620607
0.2841505092270411
--- nextGaussian ---
-0.5064310812859165
0.02500064419221778
-0.4715151970112995 

SecureRandom

SecureRandom is cryptographically strong number generator (RNG). It extends Random class. Find its sample example.
SecureRandomDemo.java
package com.concretepage;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class SecureRandomDemo {
  private static final List<Integer> VALID_PWD_CHARS = new ArrayList<>();
  static {
	IntStream.rangeClosed('0', '9').forEach(VALID_PWD_CHARS::add); // 0-9
	IntStream.rangeClosed('A', 'Z').forEach(VALID_PWD_CHARS::add); // A-Z
	IntStream.rangeClosed('a', 'z').forEach(VALID_PWD_CHARS::add); // a-z
	IntStream.rangeClosed('!', '*').forEach(VALID_PWD_CHARS::add); // !-*
  }

  public static void main(String[] args) {
	int passwordLength = 8;
	System.out.println("---Generated Password---");
	SecureRandom secureRandom = new SecureRandom();
	for (int i = 0; i < 5; i++) {
	  secureRandom.ints(passwordLength, 0, VALID_PWD_CHARS.size()).map(VALID_PWD_CHARS::get)
		  .forEach(s -> System.out.print((char) s));
	  System.out.println();
	}
  }
} 
Output
---Generated Password---
pGGyQbC1
h2cWt'yW
"EZ6AZi4
SWREGafo
tg)R5KxO 

ThreadLocalRandom

ThreadLocalRandom is a random number generator isolated to current thread. In concurrent environment we should use ThreadLocalRandom instead of Random because ThreadLocalRandom has much less overhead and contention than Random class. ThreadLocalRandom is typically used with multiple tasks of ForkJoinTask.
ThreadLocalRandomDemo.java
package com.concretepage;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.ThreadLocalRandom;

public class ThreadLocalRandomDemo {
  public static void main(String[] args) {
	ForkJoinPool pool = new ForkJoinPool();
	TestTask task1 = new TestTask("Task one");
	TestTask task2 = new TestTask("Task two");
	pool.invoke(task1);
	pool.invoke(task2);
  }
}

class TestTask extends ForkJoinTask<String> {
  private String msg = null;

  public TestTask(String msg) {
	this.msg = msg;
  }

  private static final long serialVersionUID = 1L;

  @Override
  protected boolean exec() {
	int i = ThreadLocalRandom.current().nextInt(1, 10);
	System.out.println("ThreadLocalRandom for " + msg + ":" + i);
	return true;
  }

  @Override
  public String getRawResult() {
	return null;
  }

  @Override
  protected void setRawResult(String value) {
  }
} 
Output
ThreadLocalRandom for Task one:5
ThreadLocalRandom for Task two:2 

Math.random()

Math.random() returns pseudorandom double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Find the sample example.
MathRandomDemo.java
package com.concretepage;

public class MathRandomDemo {
  public static void main(String[] args) {
    for(int i = 0; i< 3; i++) {
      double num = Math.random();
      System.out.println(num);
    }
  }
} 
Output
0.820970333540365
0.008398841915605804
0.23073775899265414 

References

Class Random
Class SecureRandom
Class ThreadLocalRandom
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us