Generate a Random number in Java

In this post we will demonstrate how to generate a random number in Java. Java provides a Random class which is in the java.util package and this allows you to generate a random number, it also allows you to specify a upper limit.

Generate a random number in Java

Below is an example showing how to print a random number

  1. random.nextInt() will produce a number between 2147483647 and -2147483648
  2. random.nextInt(boundary) will produce a number between 0 (inclusive) and your boundary provided (exclusive)

Running the above code produces the following

Generate a random number in Java with upper and lower limits

The following example shows how to generate a random number with a upper and a lower limit

Running the above code produces the following

I hope you found this post useful and it has given you an insight on how to generate a random number in Java. The Random class also has methods for you to get a random boolean, double, float and a long.

Similar Posts:

  1. How to read a properties file in Java
  2. Java 8 Streams flatMap examples
  3. Conver JSON string to a Java Object

References:

  1. Java Random API Documentation

 

Leave a Reply