Let us how to generate random number in Java. In this blog we will also learn about Random class to generate random numbers between a range of desired integers.

What is use of random numbers?

  • Game development ( android,ios,etc)
  • Creating noise for Digital signal processing software
  • Simulation

Java provides java.util.Random class which is used to generate random numbers. Let us see a very simple example of Java program to generate random numbers between 0 to 5.

Sample Java code for how to generate random number in java

import java.util.Random;

class RandomNum {
  public static void main(String[] args) {

    Random t = new Random();

    for (int i = 1; i <= 5; i++) {
      System.out.println(t.nextInt(10));
    }
  }
}

How to compile and run Java program in Linux terminal

how to generate random number in java,

  • Save the code as RandomNum.java
  • Compile using javac RandomNum.java , the javac compiler will generate a new file RandomNum.class
  • Run the java program using “java RandomNum” it will output 5 random numbers between 0 to 5 on Linux terminal screen
bosch@bosch-Inspiron-N5050:/sample$ java RandomNum 
9
4
3
5
0

How to generate random numbers between a range of desired integers

import java.util.Random;

class RandomNum {
  public static void main(String[] args) {
    
    Random r = new Random();
    
    // range between 10 to 15
    int max = 15;
    int min = 10; 

    // nextInt is exclusive of the max value,
    // so add 1 to make it inclusive

    for (int i = 1; i <= 5; i++) {
      System.out.println(r.nextInt(max - min + 1 ) + min );
    }
  }
}

How it works

  • r.nextInt(max – min +1 ) ,this statementĀ  will generate random number from 0 to (max -min + 1) [15-10 +1 = 6], where 6 is exclusive.
  • HenceĀ  r.nextInt(max – min + 1 ) + min, will generate random numbers between 10 to 15.

Ref:

https://docs.oracle.com/javase/8/docs/api/java/util/Random.html



Related Contents to follow