Java Random Integer

It is required random numbers in many applications like lotteries, testing programs, pick up names from a group etc. It is permitted to generate Java random integer, random double with the class java.util.Random.

Random class can generate three variations of random numbers.

1. At different times of execution, different random numbers
2. At different times of execution, same set of random numbers
3. Random numbers within a range (1 to given number or between two given numbers)

Following Example on Java Random Integer illustrates all the above three.
import java.util.Random;
public class RandomIntegerGeneration
{
  public static void main(String args[])
  {
    Random rand1 = new Random();
     
    System.out.print("\nGenerating 1st variation: ");        // 1st variation 
    for(int i = 0; i < 5; i++)                               // generating different random integers 
    {                                                        // at different times of execution
      System.out.print(rand1.nextInt()+" ");                                  
    }

    System.out.print("\n\nGenerating 2nd variation: ");
    Random rand2 = new Random(100);                          // generating same set of random integers 
    for(int i = 0; i < 5; i++)                               // at different times of execution                        
    {
      System.out.print(rand2.nextInt()+" ");                                  
    }

    System.out.print("\n\nGenerating 3rd variation Printing 1 to 100: ");
    for(int i = 0; i < 5; i++)                             
    {
      System.out.print(rand1.nextInt(100)+" ");                                  
    }

    System.out.print("\n\nGenerating 3rd variation Printing 50 to 150: ");
    int startRange = 50, endRange = 150;
    for(int i = 0; i < 5; i++)
    {
      int offsetValue =  endRange - startRange + 1;
      int  baseValue = (int)  (offsetValue * rand1.nextDouble());
      int k =  baseValue + startRange;
      System.out.print(k + " ");
    }
  }
}

Java Random IntegerOutput Screenshot on Java Random Integer

rand1.nextInt() generate both positive and negative numbers. If wanted only positive, use Math.abs(rand1.nextInt());
nextInt(100): Prints 1 to 100. Pass the given number to the parameter of nextInt() method.
Getting random numbers between two numbers is a logical code self-explanatory.

For more detailed explanation with class signature and where to use which variation etc., see this link: class Random.

Leave a Comment

Your email address will not be published.