How to generate a random number using a Java program?

Random number in java can be easily be generated in two ways:

  1. Math class
  2. Random class

nextInt(int MAX) instance method of Random (java.util.Random) class returns a random integer less than MAX and nextDouble() returns the random double value between 0 and 1.

Similarly, you can use nextFloat(), nextLong(), nextShort() etc.

Let’s see some example of them in Java.


Static random() method of Math (java.lang.Math) class can also be used to generate a random number in Java.

Since random() is a static method we don’t need to create an instance of Math class.

Let’s see some examples using Math.random() method in Java.


Comment below your suggestion or doubts.

Leave a Reply

eleven − 2 =