Last Updated: 14 August, 2022

On this page, we are going to learn how to write a Java programme to print a random number.

We will use three different approaches to print a random number in Java as given below.

👉 Using the *java.util.Random* class

👉 Using the *Math.random()* method

👉 Using the *java.util.concurrent.ThreadLocalRandom* class

We need to create an instance of the java.util.Random class first and then call methods such as nextInt(), nextDouble(), nextLong(), etc. with the help of that instance. We can pass parameters to the methods for placing an upper bound on the range of the numbers to be generated. For example, nextInt(5) will generate numbers in the range of 0 to 4, both inclusive.

Let's see the example below to understand the implementation.

Output

5 Random Numbers are:

===================

182

232

451

855

161

The Math class is a class of the lang package. It contains many methods to perform different operations. It has a method that prints the random number. That method's name is the random() method. This method returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. The returned values are chosen pseudorandomly.

Let's see the example below to understand the implementation.

Output 1:

Random number: 0.9186058314975933

Output 2:

Random number: 0.45593204214380434

The ThreadLocalRandom class was introduced in the Java 1.7 version and placed in the java.util.concurrent package. This class can generate random numbers of types such as integers, doubles, booleans, etc.

Let's see the example below to understand the implementation.

Output

Random Integer 1: -1503823616

Random Integer 2: -1345710525

Random Integer 3: -1818189431

Random Double 1: 0.5139741611423724

Random Double 2: 0.0833277782528794

Random Double 3: 0.5313404603108741

Random Boolean 1: true

Random Boolean 2: false

Random Boolean 3: false

That's all guys, hope this Java Program is helpful for you.

Happy Learning... 😀

If you have any query or suggestion regarding this artical please share with us

`feedback@javabytechie.com`