How to Generate a Random Number in Java

The Java programming language is a powerful tool in computer science, providing limitless possibilities for all types of programs. Among Java's many features is the ability to generate random numbers, in both Integer and Floating Point format. This guide will go through the steps required to initialize this functionality and generate random numbers.

Things You'll Need

  • Computer with Java installed
  • Java development environment you are familiar with
Show More

Instructions

  1. Importing and Initializing Random

    • 1

      Open the Java file the random number functionality will be used in. This Java file can be a new program or an existing one.

    • 2

      Type the following line of code into the Java file, above the class declaration for this Java file:
      import java.util.Random;
      This line will import the Random library package required to generate random numbers.

    • 3

      Create an instantiation of the Random class, which allows access to methods for generating random numbers. An example of instantiation code for Random is:
      Random generator = new Random();
      Once instantiated, the Random methods can be used to generate random numbers.

    Generating Random Numbers

    • 4

      Create a random integer by calling the Random method nextInt(). This method will return an integer from the valid range of Java integers. An example of calling this method is:
      int r = generator.nextInt();

    • 5

      Create a random floating point by calling the Random method nextDouble(). This method will return a value between 0 and 1, but will never return 0 or 1. An example of calling this method is:
      double s = generator.nextDouble();

    • 6

      Create a random Gaussian by calling the Random method nextGaussian(). This method will return a number from a normal distribution, given a mean of 0 and a standard deviation of 1. An example of calling this method is:
      int t = generator.nextGaussian();

Tips & Warnings

  • The Random class, like all random number generators, is seeded upon instantiation. The default seed is the current time, but other seeds can be used. When instantiating Random, any Long Integer can be used as the seed by providing it as a parameter in Random's constructor. To generate a random integer between 0 and n-1, use n as a parameter in the nextInt() method. Random numbers can be translated and scaled, once created. This allows the numbers to be used for a variety of applications.

  • It is important to note random number generators do not actually generate random numbers. The numbers generated completely depend on the seed value given, typically the current time, when Random is instantiated.

Related Searches:

References

Resources

Comments

You May Also Like

Related Ads

Featured