ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

How to Generate Random Numbers in Java

Updated on August 25, 2011

Java Random Numbers Overview

I will introduce you to random numbers in Java. First I'll give you what you came here for: ready made examples, then I'll go behind the scenes of random number generation in Java. I will go over each method that generates a "random" number in Java. I will explain why the numbers generated are not really random, and how normal distribution is related to random numbers in Java.

So without much delay here is an example that covers every method of generating a Random number in standard Java (as of this writing JDK and JRE 6 are in their 22nd update release) installation on Windows (Note that a statement new java.util.Random is used when you call Math.random(), that's why all my examples use use java.util.Random package).

Java Random Numbers Code Sample

package MathRandom_Java;
import java.util.Random;


public class Java_Math_Random_All
{
 public static void main( String...strings )
 {
  // Create a new instance or object of class Random
  Random util_Random = new Random();

  // Generate a pseudorandom number between 0.0 and 1.0 
  // (Note: number will in the range of 0.0 to 1.0, but never 1.0) 
  double  util_Random_Double  = util_Random.nextDouble();
  
  // Returns the next pseudorandom, Gaussian ("normally") distributed 
  // double value with mean 0.0 and standard deviation 1.0
  double  util_Random_Gaussian  = util_Random.nextGaussian();
  
  // Generate a number between 1.40129846432481707e-45 
  // to 3.40282346638528860e+38 (positive or negative)
  float   util_Random_Float  = util_Random.nextFloat();
  
  // Generate a number between -9,223,372,036,854,775,808 
  // to +9,223,372,036,854,775,807
  long    util_Random_Long  = util_Random.nextLong();
  
  // Generate a number between -2,147,483,648 to 2,147,483,647
  int     util_Random_Integer  = util_Random.nextInt();
  
  // Generate an integer from a specified range (if your pass 
  // in n as a parameter you numbers will range from 0 to n-1)
  int     util_Random_Integer_from_n = util_Random.nextInt(32);
  
  // Generate either true or false pseudorandomly
  boolean util_Random_Bool = util_Random.nextBoolean();
  
  // Create and initialize an array of 5 bytes 
  byte[] bytes = new byte[5];
  // Populate the array with 5 randomly generated bytes
  // Note: byte is a value that ranges from -128 to 127
  util_Random.nextBytes( bytes );

  // Creates a java.util.Random object and calls 
  // the nextDouble() method
  double math_Random = Math.random();

  // Display all the results from above methods
  System.out.println( "Math.random() -> " + math_Random );

  System.out.println( "nextDouble() ->" + util_Random_Double );
  System.out.println( "nextGaussian() -> " + util_Random_Gaussian );
  System.out.println( "nextFloat() -> " + util_Random_Float );
  System.out.println( "nextLong() -> " + util_Random_Long );
  System.out.println( "nextInt() -> " + util_Random_Integer );
  System.out.println( "nextInt(n) -> " + util_Random_Integer_from_n );
  System.out.println( "nextBoolean() -> " + util_Random_Bool );
  System.out.println( "nextBytes(bytes) -> " );
  for( int i = 0; i < bytes.length; i++ )
   System.out.println( "Byte " + (i+1) + ": " + bytes[i] );
 }
}

Sample Output

Math.random() -> 0.008014059073862545
nextDouble() -> 0.4017283520137178
nextGaussian() -> -0.5345105808614735
nextFloat() -> 0.6654831
nextLong() -> 982543587599054257
nextInt() -> -502464678
nextInt(n) -> 3
nextBoolean() -> true
nextBytes(bytes) ->
Byte 1: 62
Byte 2: -83
Byte 3: -93
Byte 4: 114
Byte 5: -109

nextInt

First notice that depending on your needs, all you may be looking for is generating a simple random integer in the range of your choosing.

For that purpose I recommend that you use nextInt(int n) method. Just remember that if you want to generate numbers from 0 to n pass a number that is equal n + 1.

For example if I want to generate numbers in the range of 0 to 32 I would pass 33 like so: nextInt(33)


And if I wanted to limit my lower range, I would add a number to what I generate from nextInt(int n), and subtract the same number from n. For example nextInt(33-10)+10 would generate numbers in the range of 10 to 32.

nextInt Code Sample

package MathRandom_Java;
import java.util.Random;


public class Java_Math_Random_Int
{
 public static void main( String...strings )
 {
  // Create a new instance or object of class Random
  Random util_Random = new Random();

  // Generate an integer from a specified range (if your pass 
  // in n as a parameter your numbers will range from 0 to n-1)
  int pseudorandom_Integer = util_Random.nextInt(32+1);
  System.out.println( "nextInt( n ) -> " + pseudorandom_Integer );
  
  // Generate an integer from 10 inclusive to 32 exclusive. 
  pseudorandom_Integer = util_Random.nextInt(33-10) + 10;
  System.out.println( "nextInt( n-10 ) + 10 -> " + pseudorandom_Integer );
 }
}

Sample Output

nextInt( n ) -> 27
nextInt( n-10 ) + 10 -> 16

Java Random is Not Random

Generating a random number on a computer is not random at all. There is an algorithm that takes number of milliseconds that have passed starting from UNIX epoch. Since the number of milliseconds always changes, a number generated from the numerous random methods in Java, seems to be random.

If you were to manually pass in the number of milliseconds (a seed value) to the Random class instance or object, you would see that every time you generate a "random" value you get the same result! Run this code repeatedly to see what I mean:

package MathRandom_Java;
import java.util.Random;


public class Java_Math_Random_Seed
{
 public static void main( String...strings )
 {
  // Create a new instance or object of class Random
  Random util_Random = new Random();
  // If you manually set the seed for your Random object,
  // the value generated will be the same on each run.
  util_Random.setSeed( 555 );

  // Generate a pseudo random number between 0.0 and 1.0
  // (Note: number will be in the range of 0.0 to 1.0,
  // but never 1.0)
  double  util_Random_Double  = util_Random.nextDouble();

  System.out.println( "nextDouble() ->" + util_Random_Double );
 }
}

Sample Output - The Same on All Computers

nextDouble() ->0.6816084544091354

Uniform vs Normal Distributions in Java Random Methods

Another point to consider is that almost all random methods in Java use uniform distribution method for the their values. Which in plain English means that the probability to select a pseudo random number from all the possible random numbers that a computer can produce is going to be the same.

The exception to this rule is the method called nextGausian() which generates a pseudo random number based on normal distribution. Translation into simpler language yields: values generated from nextGausian() are biased toward the most probable, and he most probably is 0. For example 0.5 is much much more probable to appear to be generated from nextGaussian() than say 0.0005.

Normal Distribution Blurb

It forms a bell shaped curve, which is also called a normal curve. Almost everything in nature (including human behavior, like watching TV) occurs according to this normal curve (if measured and graphed).

The normal curve could by itself take up a lot of volumes of writing and is not going to be covered in this article, so suffice it to say that if you wanted to make an application that would simulate a Natural behavior you would use nextGaussian() method.

Last Words

To sum it all up, there three basic things you have to be aware of when generating pseudo random values:

  1. Most methods use uniform distribution, but there is one method that uses normal or Gaussian distribution called nextGaussian().
  2. If you simply want to generate a pseudo random range of positive integers from zero to some number n then use nextInt( n+1 ).
  3. Alternatively if you want to generate a pseudo random range of positive integers from some number m to some number n, then use nextInt(n-m)+m, given that m is less than n.

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)