Generate Random numbers in Java

Generating Random numbers in java is quite easy as it provides various classes to do that. It comes handy when needed to apply on any kind of application development that might require random number generation. Let start by knowing random numbers.

What is Randon Number?

We can define Random as something that happens without any conscious decision. Similarly, a random number is a number that is chosen unpredictably or randomly from the set of numbers.

Random Number can be generated using two ways.

  • java.util.Random class
  • Math.random() method

We will also learn to generate between the range, at last.


Java Program to generate Random Number.

1. Using java.util.Random class:

java.util.Random class allows us to generate random numbers of type integers, doubles, floats, longs and booleans. In the example below, we will see to generate numbers of type Integers and booleans. Then you can apply to other data-types.

Program:

The output of generating random numbers using java.util.Random class:

Randon Number generator java.util.Random

2. Using Math.random() method:

Math.random() method allows you to create an only a random number of type doubles as shown below.

Program:

The output of generating random numbers using Math.random() method:

Random Number Generator using Math.random() method

Java Program to generate Random Number within the range:

The output to generate random numbers between the range in java:

This random generation of numbers within range can be applied to Math.random() method, we only need to replace the code inside the for loop to System.out.println((int)(Math.random() * lastNum));.