Java How To Generate Random Numbers

How To Generate a Random Number

You can use Math.random() method to generate a random number.

Math.random() returns a random number between 0.0 (inclusive), and 1.0 (exclusive):

Example

Math.random();

 

To get more control over the random number, for example, if you only want a random number between 0 and 100, you can use the following formula:

Example

int randomNum = (int)(Math.random() * 101); // 0 to 100