How to generate random number in java

This section shows you how to create a random number and example provided here will help you easily understand and use the code to generate random numbers in your java application.

How to generate random number in java

This section shows you how to create a random number and example provided here will help you easily understand and use the code to generate random numbers in your java application.

How to generate random number in java

How to generate random number in java

In this section you will learn how to generate random number in java. Java API  provide a random class in java.util.Random package which generate random number within a range. The random() method is most convenient way to generate random number in java which return only double value .You can also generate pseudo-random floating or double type numbers.

Random Numbers in Java with Example

As we discussed that to create a random number, java provide a random() method in java.util.Random class. You have to create the instance of random class. This class provide method to return random integer, double and float. The following example will illustrate the random number generation in java.

import java.util.Random;
public class RandomNumber 
{
 public static void main(String args[])
 {
   Random random = new Random();
   for(int i =0; i<5; i++){
   int randomInteger = random.nextInt();
   System.out.println("Random Integer in Java: " + randomInteger);
  }
 }
}

As this program execute it will generate five random numbers. If you are using java Math.random  it will generate only double value not integer. Some of the methods of Random class are as follows :

  • next(int num) - Generate next pseudorandom number.
  • nextBoolean() - Returns the next pseudorandom, boolean values.
  • nextInt() -  Returns all pseudorandom integer type in equal probability.
  • nextDouble() - Similar to integer it returns in double with range 0.0 to 1.0.
  • nextFloat() - Returns pseudorandom float values with range from 0.0 to 1.0.
  • nextLong() - Returns pseudorandom long value in the sequence.

So,  if you will compile and execute the program then you will  get the output as follows:

Download Source Code