Java Programming Random Number Generator

Java Generating Random Value

  • java.util.Random class provides the methods to generate the pseudorandom number for different data types.
  • Random class is the sub class of Object class which is the root class in java.
  • An instance of Random class is used to generate a stream of pseudorandom numbers.
  • Random class instances are threadsafe but concurrent use of the same java.util.Random instance across threads may encounter poor performance. ThreadLocalRandom class is available in java for multithreaded designs.
  • Random class instances are not secure cryptographically. SecureRandom class is available in java to get a cryptographically secure pseudo-random number generator. this SecureRandom class can be used for security-sensitive applications.
public class Random extends Object implements Serializable

How to generate random integer in java?

next method in Random class - next method is protected access in Random class returns integer random number.
protected int next(int bits)

Java program to generate random integer using next method of Random class

import java.util.*;                                                             
                                                                                
class JavaRandom3 extends Random{                                               
 public static void main(String args[]) {                                       
    JavaRandom3 random = new JavaRandom3();                                     
    for(int i=1; i<=5; i++) {                                                  
        System.out.println("Random Integer" + i + ": " + random.next(8));       
    }                                                                           
 }                                                                              
} 
Output:
$ java JavaRandom3
Random Integer1: 198
Random Integer2: 224
Random Integer3: 61
Random Integer4: 202
Random Integer5: 22
Random.nextInt method - returns the next pseudorandom integer.
public int nextInt()

Java program to generate random integer

import java.util.*;                                                             
                                                                                
class JavaRandom {                                                              
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                   
        System.out.println("Random Integer" + i + ": " + random.nextInt());     
    }                                                                           
 }                                                                              
}  
output:
$ java JavaRandom
Random Integer1: -1689153053
Random Integer2: -1691680029
Random Integer3: 1952187265
Random Integer4: 103298371
Random Integer5: -356456947

How to generate random integer in between 0 and limit parameter(max integer value)?

Random.nextInt(limit)- returns pseudorandom integers between 0 to limit which can be specified as parameter
int nextInt(int limit)

Java program to generate random integer between 0 to limit(max integer value).

.
import java.util.*;                                                             
                                                                                
class JavaRandom1 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=10; i++) {                                                   
        System.out.println("Random Integer" + i + ": " + random.nextInt(10));   
    }                                                                           
 }                                                                              
} 
Output:
$ java JavaRandom1
Random Integer1: 5
Random Integer2: 3
Random Integer3: 8
Random Integer4: 1
Random Integer5: 4
Random Integer6: 0
Random Integer7: 5
Random Integer8: 8
Random Integer9: 5
Random Integer10: 5

How to generate random long integer?

nextLong method in Random class - returns the next pseudorandom long integer value
public long nextLong()

Java program to generate random long integer

import java.util.*;                                                             
                                                                                
class JavaRandom2 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                  
        System.out.println("Random Long Integer" + i + ": " + random.nextLong());
    }                                                                           
 }                                                                              
}    
Output:
$ java JavaRandom2
Random Long Integer1: 6204425201330476624
Random Long Integer2: 3939077056305662022
Random Long Integer3: -6116547507993421664
Random Long Integer4: -5425591754091129004
Random Long Integer5: 733576223822010011

setSeed method in Random class

Sets the seed of this random number generator using a single long seed.
void setSeed(long seedValue)

Java program to generate random long integer using setSeed method

import java.util.*;                                                             
                                                                                
class JavaRandom2 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                   
        if(i==5) {                                                              
            random.setSeed(100);                                                
        }                                                                       
        else {                                                                  
            random.setSeed(7366551435105484086L);                               
        }                                                                       
        System.out.println("Random Long Integer" + i + ": " + random.nextLong());
    }                                                                           
 }                                                                              
}  
Output:
$ java JavaRandom2
Random Long Integer1: -1302919629888628344
Random Long Integer2: -1302919629888628344
Random Long Integer3: -1302919629888628344
Random Long Integer4: -1302919629888628344
Random Long Integer5: -5128016860359238732

How to generate random boolean value?

nextBoolean method in Random class - returns the next pseudorandom boolean value.
boolean	nextBoolean()

Java program to generate random boolean value

import java.util.*;                                                             
                                                                                
class JavaRandom4 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                  
        System.out.println("Random " + i + ": " + random.nextBoolean());        
    }                                                                           
 }                                                                              
}  
Output:
Random 1: false
Random 2: false
Random 3: false
Random 4: true
Random 5: true

nextBytes method in Random class

randomly generated bytes and assign into a user-supplied byte array.
void nextBytes(byte[] bytes)

Java program to generate random bytes

import java.util.*;                                                             
                                                                                
class JavaRandom5 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                  
        byte[] bytes = new byte[100];                                           
        random.nextBytes(bytes);                                                
        System.out.println("Random " + i + ": " + bytes);                       
    }                                                                           
 }                                                                              
} 
Output:
$ java JavaRandom5
Random 1: [B@15db9742
Random 2: [B@6d06d69c
Random 3: [B@7852e922
Random 4: [B@4e25154f
Random 5: [B@70dea4e

How to generate random float number?

nextFloat method in Random class - returns the next pseudorandom float value between 0.0 and 1.0.
float nextFloat()

Java program to generate random float value

import java.util.*;                                                             
                                                                                
class JavaRandom6 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                  
        System.out.println("Random Float" + i + ": " + random.nextFloat());          
    }                                                                           
 }                                                                              
} 
Output:
$ java JavaRandom6
Random Float1: 0.074386775
Random Float2: 0.9043543
Random Float3: 0.48675168
Random Float4: 0.5216956
Random Float5: 0.037228405

How to generate random double value?

nextDouble method in Random class - returns the next pseudorandom double value between 0.0 and 1.0.
double nextDouble()

Java program to generate random double number

import java.util.*;                                                             
                                                                                
class JavaRandom7 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                  
        System.out.println("Random double" + i + ": " + random.nextDouble());   
    }                                                                           
 }                                                                              
} 
Output:
$ java JavaRandom7
Random double1: 0.1232464994256951
Random double2: 0.7140631066463907
Random double3: 0.9438924024885673
Random double4: 0.24870371110216516
Random double5: 0.5521996971170559

Math.random - Alternate way to generate random number except using Random class

Math.random method is also available but it generates double random numbers.

Java program to generate random double number using Math.random method

import java.util.*;                                                             
                                                                                
class JavaRandom2 {                                                             
 public static void main(String args[]) {                                       
    //Random random = new Random();                                             
    for(int i=1; i<=5; i++) {                                                  
        //System.out.println("Random double" + i + ": " + random.nextInt(10)); 
        System.out.println("Random double" + i + ": " + Math.random());        
    }                                                                           
 }                                                                              
}                                                                               
Output:
$ java JavaRandom2
Random double: 0.3276202477160206
Random double: 0.05003947696588251
Random double: 0.957158207424922
Random double: 0.053595606471153134
Random double: 0.030469717460436252

How to generate random gaussian double value?

nextGaussian method in Random class< - returns the next pseudorandom double value Gaussian ("normally") with mean 0.0 and standard deviation 1.0.
public double nextGaussian()

Java program to generate Gaussian random double number

import java.util.*;                                                             
                                                                                
class JavaRandom8 {                                                             
 public static void main(String args[]) {                                       
    Random random = new Random();                                               
    for(int i=1; i<=5; i++) {                                                  
        System.out.println("Random double" + i + ": " + random.nextGaussian()); 
    }                                                                           
 }                                                                              
}  
Output:
$ java JavaRandom8
Random double1: -0.2384602405147781
Random double2: 1.2574930592267088
Random double3: -0.27873686337275844
Random double4: 1.7361407368198931
Random double5: 1.0019820158656176

Java Programming Examples

GCD and Rational Number Java Program

Java Queue Program using exception

Java Stack Program using exception

Addition of three integers java program

Biggest of three integers java program

Fibonacci numbers java program

Arithmetic Operations Menu java program

Second Smallest Element In Array Java Program

Transpose Of A Matrix Java Program

Java Program to Display triangle of stars (*)

Java Programming Prints Product Tables

Java Program to Display triangle of numbers

Java Programming Gets Current Date

Java Programming Finds Character Vowel or Consonent

Java Programming HCF and LCM Computation

Java Programming Sum of Command Line Integer Arguments

Java Programming Multiplication of Command Line Integer Arguments

Java Programming Multiplication of Command Line Floating Point Numeric Arguments

Java Programming String Contains or Not

Java Programming Gets Grade Description using Switch

Java Programming CSV File Reader

Java Programming Character Frequency Count in String using for each

Java Programming Finds Min from Integer Array by Passing Array to Method

Java Programming Linear Search

Java Programming Binary Search

Java Programming Ternary Search

Java Programming Generates Range of Numbers

Java Programming Generates Range of Characters

Java Programming Computes Square Root Value

Java Programming Checks Number is Positive or Negative

Java Programming Checks Number is Odd or Even

Java Programming Computes Plot Area

Java Programming Convert Number of Days into Years

Java Programming Checks a Year is Leap Year, Century Year or Not

Java Programming Checks a Character is Digit, Letter or neither digit nor letter

Java Programming Checks a Number is Palindrome or not

Java Programming Sum of Two Matrix

Java Programming Power Computation

Java Programming Checks Number is an Armstrong Number or not

Java Programming Temperature Unit Conversions

Java Programming Generates Random Numbers in Specified Range

Java Programming Computes Sum of Digits and Product of Digits

Java Programming Computes Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Programming Computes Harmonic Series

Java Programming Generates Floyd's Triangle

Java Programming Reverses String

Java Programming Checks Palindrome String or not

Java Programming Opens Notepad

Java Programming Searches String using RegEx Pattern

Java Programming Searches Word in String

Java Programming Gets System Environment Variables

Java Programming Gets IP Address of Server Name

Java Programming Arrays Sort and Reverse using sort method

Java Programming Bubble Sorting

Java Programming Selection Sorting

Java Programming Insertion Sorting

Java Programming Merge Sorting

Java Programming Quick Sorting

Java Programming Counting Sort

Java Programming Radix Sorting

Java Programming Sorting Array of Strings

Java Programming String Characters Sorting

Java Programming Sum of First N Numbers

Java Programming Product of First N Numbers

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^