Last Updated:

How to Generate a Random Number in Java

Often in novice Java-programmers the question of generating a random number is recognized. Therefore, in this article you will learn the best way to generate a random number in Java from 0 to N.

Note: If you don't want to include zero in the list of possible generated numbers, then just add one to the result.

Step 1 – Import the Java Random class.

Step 2 − Create an instance of the Random class.

Step 3 – Call the nextInt() method.

The nextInt() method takes an integer parameter. It generates a random number from 0 to that number, but does not include that number. For example, the following command generates a random number between 0 and 9:

Complete java random number generation example

This program prints 100 random numbers from 0 to 9:

Conclusion: Today we generated a random number in Java. Stay tuned.