Katerina Zamani

About Katerina Zamani

Katerina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she attends MSc courses in Advanced Information Systems at the same department. Currently, her main academic interests focus on web applications, mobile development, software engineering, databases and telecommunications.

Java random number generator Example

Java provides us the opportunity to generate pseudo-random numbers with two ways:

Random class provides also a random number generation by using a single long seed. So, two different instances of Random class that are initialized with the same seed and call the same sequence of methods, will return identical sequences of random numbers.

In this example we are going to show how to produce random integer and double numbers specified into a range or not, as well as the use of seed.

1. Example of random number generator

Create a java class with name RandomNumberClass and paste the following code.

RandomNumberClass.java:

package com.javacodegeeks.core.random;

import java.util.Random;

public class RandomNumberClass {

	public static void main(String[] args) {
		
		 Random generateRand = new Random();
		 
		 System.out.println("Generate random numbers:");
		 for(int i=0; i<3; i++){
		      System.out.printf("%d ",generateRand.nextInt());
		      System.out.println(" "+generateRand.nextDouble());
		 } 

		 //set ranges
		 Random generateRange = new Random();
		 
		 System.out.println("\nGenerate random int [1,10] and double [0.0,360.0):");
		 for(int i=0; i<5; i++) {
			 int num = generateRange.nextInt(10)+1;
			 double angle = generateRange.nextDouble()*360.0;
			 System.out.println(" num = "+num+" and angle = "+angle);
		 }
		 
		 Random generateGaus = new Random();
		 System.out.println("\nGaussian random =  "+generateGaus.nextGaussian()+"\n"); 
		 
		 Random seed1 = new Random(5);
		 for(int i=0; i<3; i++) {
			System.out.println("seed1 = "+seed1.nextInt()); 
		 }
		 System.out.println("--------------------");
		 Random seed2 = new Random(5);
		 for(int i=0; i<3; i++) {
			System.out.println("seed2 = "+seed2.nextInt()); 
		 }
	}

}

Lets explain the code above. Random class provides us functions in order to take the next peudorandom number. As you can notice we use nextInt() and nextDouble() methods in order to generate int and double random values respectively. nextInt() method can return a positive or negative random number between all the possible 2^32 int values. On the other hand, nextDouble() function generates double numbers greater than or equal to 0.0 and less than 1.0.

Also, we can produce random numbers from a specific range. For this reason we have to set the appropriate numbers or/and make some operations (multiply/add). In our example we want to produce random integer numbers that belong to [1,10] range. Firstly nextInt(10) is called and +1 is added to the returned value. Essentially, nextInt(n) returns a random between 0 (inclusive) and the specified value n (exclusive) - 10 in our occasion. So n is not included in the list of picked numbers and for this reason we should add value 1, in order to have the desirable range. If we want a specific range for double values for example, there isn't any builtin function for ranges in this situation, so we should multiply/add the returned random with the appropriate values. As you can see in the code above, we want to produce angles - the range is [0.0, 360.0) - so we multiply with the double 360.0.

In addition Random class contains the nextGaussian() method, which returns a random double number with a normal distribution with mean 0.0 and deviation 1.0.

Finally, notice that we initialize two instances of Random class with the same seed. As we explained above, the sequence of seed1 will be identical to the sequence of seed2, since we make the same calls for both instances. So, if the seed is known we can find out which numbers are going to be generated in a specific algorithm and this can be a very important information for some apps.

Now you can see the output of the above execution. Please, notice that the random values are contained to the respective ranges. Also, we can ascertain that the sequence of the instances seed1 and seed2 are the same.

Output:

Generate random numbers:
-906587502  0.47291343028193733
1282976872  0.9810376969317285
-1650541178  0.47312499538673947

Generate random int [1,10] and double [0.0,360.0):
 num = 8 and angle = 29.3332477431203
 num = 6 and angle = 114.05670201967776
 num = 6 and angle = 140.71230065866766
 num = 7 and angle = 354.5249452932836
 num = 10 and angle = 159.76422587013093

Gaussian random =  0.9854270231907662

seed1 = -1157408321
seed1 = 758500184
seed1 = 379066948
--------------------
seed2 = -1157408321
seed2 = 758500184
seed2 = 379066948

Download the source file

This was a tutorial about random number generator in Java. Download the source code of this example: RandomNumberExample.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books