How to generate random numbers in Java

Minhajul Alam
2 min readDec 10, 2018

There are many ways to create random numbers in java. One of them is to use the java.util.Random class.

Generating random numbers using java.util.Random class

First of all we have to create an instance of the Random class and then we have to invoke methods such as nextInt(), nextLong(), nextFloat(), nextDouble(), nextBoolean() etc.

We can generate integer, float, double, boolean types random numbers.

Code:

import java.util.Random;

public class RandomNumberGenerator {
public static void main(String args[]){

Random rand = new Random();

int randomInteger;

randomInteger = rand.nextInt();

System.out.println(randomInteger);



}
}

Output:

-418008778

How to generate random numbers in a given range

To generate random numbers in a range, we can specify upper bound by passing arguments to the method.

For example, nextInt(10) will generate numbers in the range 0 to 9 inclusive.

Code:

import java.util.Random;

public class RandomNumberGenerator {
public static void main(String args[]){

Random rand = new Random();

int randomInteger;
int upperLimit = 10;
randomInteger = rand.nextInt(upperLimit);

System.out.println(randomInteger);



}
}

Output:

5

If we want to generate numbers 1 to 10 we can add one with the generate random number. Then it will show random number 1 to 10 inclusive.

Code:

import java.util.Random;

public class RandomNumberGenerator {
public static void main(String args[]){

Random rand = new Random();

int randomInteger;
int upperLimit = 10;
randomInteger = rand.nextInt(upperLimit)+1;

System.out.println(randomInteger);
}
}

Output:

10

We can also set the lower limit. For this, we have to add the lower limit with the random number.

import java.util.Random;

public class RandomNumberGenerator {
public static void main(String args[]){

Random rand = new Random();

int randomInteger;
int lowerLimit = 5, upperLimit = 10;
randomInteger = lowerLimit + rand.nextInt(upperLimit);

System.out.println(randomInteger);
}
}

We can also use this code.

int randomInteger = Math.random()*((upperLimit-lowerLimit)+1)+lowerLimit;

Now we will make Random Number Generator in Android.

--

--