How to generate random numbers between 1 to 100 in Java?

Abdur Rahman | TN Career Path
2 min readNov 3, 2023

--

Random Numbers in JAVA are generated in 2 different ways,

we can use Math Class or Random Class.

In this we will use Random to generate random numbers.

Random Number Generations

Random number generation in Java is accomplished using the java.util.Random class.

To import:

import java.util.Random;

Constructor Summary

Constructor and Description

Random()

Creates a new random number generator.

Random(long seed)

Creates a new random number generator using a single long seed.

Some of the Methods Available in Random Class

nextInt()

Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.

nextInt(int bound)

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.

nextLong()

Returns the next pseudorandom, uniformly distributed long value from this random number generator's sequence.

setSeed(long seed)

Sets the seed of this random number generator using a single long seed.

Code

To generate random numbers between 1 to 100 in Java

package RandomNumberGenerator;

import java.util.Random;
import java.util.Scanner;

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

int low, high;
int n;
int number;

Scanner sc = new Scanner(System.in);
Random rand = new Random();

System.out.println("Enter start number : ");
low = sc.nextInt();

System.out.println("Enter end number : ");
high = sc.nextInt();

System.out.println("Enter no. of numbers to be generated : ");
n = sc.nextInt();

System.out.println("=====================================================");
System.out.println("Generated Random Numbers");

for (int i = 0; i < n; i++) {
// include low but exlude high = rand.nextInt(high-low)+low
number = rand.nextInt((high + 1) - low) + low; // includes both high and low
System.out.println(number);
}
}
}

OUTPUT

Random for generating random numbers and Scanner for taking user input.

It defines several variables:

low: The lower limit of the range for random number generation.
high: The upper limit of the range for random number generation.
n: The number of random numbers to generate.
number: A variable to store each generated random number.

Thank You! Follow me for more

--

--

Abdur Rahman | TN Career Path

πŸ‘¨β€πŸ’» Passionate tech explorer 🌐 | Constantly curious about the digital universe πŸš€ | Join me on my journey through world of computer science and technology!