That’s a small java tutorial that might help you out to create random numbers in java.

First of all how to create a random number in java?

easy, here’s the codes:

float random = Math.random();

This statement will generate a random number between 0 and 0.999999… But u may want a bigger range of values and maybe you want it to be an integer instead of a float. No panic here’s the trick.


for integers , u have to Cast if first using (int) :

int random = (int) Math.random();

Note that this statement will always return 0.

Range your random Integer Between x and y:

Let’s take this example, you want a random number between 2 and 10.

so x = 2 and y = 10 :

int random = (int) ( 2 + Math.random() *8);

this will generate a random number between 2 and 10 !!

Here’s the general formulas:

LowerBound <= random < UpperBound

int random = (int) (Lower_Bound + Math.random() * ( Upper_Bound - Lower_bound) );

LowerBound <= random <=UpperBound

int random = (int) (Lower_Bound + Math.random() * ( Upper_Bound - Lower_bound) + 0.5) ;

Need more java tutorials ? check this out.