How to generate random number between two numbers in Java ?

This post demos how you can get the random number between two numbers in a simple java program. When you are feeding some dummy data to something, you are required to simulate the inputs for your project / product. So mostly this random numbers are used in such scenarios.

$ vim RandomNumber.java 
import java.lang.Math;

public class RandomNumber {
        public static void main(String[] args) {
                int max = 250;
                int min = 100;
                int random = (int) (Math.random() * (max - min)) + min;
                System.out.println(random);
        }
}

As we can see above, this program prints the random number between minimum number 100 and maximum number 250 using Math library random function. Math library random function returns float random number between 0 and 1, hence we multiplied to it the difference between maximum and minimum numbers and added the minimum number to it so we remain above minimum but below maximum.

Compile this program as,

$ javac RandomNumber.java

Now, if you run this java program from console as below, you can see the random number printed on console which is always within the maximum and minimum.

$ java RandomNumber 
247
$ java RandomNumber 
164
$ java RandomNumber 
153
$ java RandomNumber 
237

Leave a Comment