Java Generate random numbers in a specific range

 Posted On  | Yashwant Chavan 

In this tutorial, You will learn how to Generate random numbers in a specific range using Java. We will use Random.nextInt(int bound) method to generate random numbers.

Generate Random Numbers using Random.nextInt() method

Refer below steps

  • java.util.Random - An instance of this class is used to generate a stream of pseudorandom numbers.
  • Random.nextInt(int bound) method returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.
package com.technicalkeeda.app;

import java.util.Random;

class GenerateRandomNumber {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            System.out.println("Random Number:- " + randomNumberInRange(50, 100));
        }
    }

    public static int randomNumberInRange(int min, int max) {
        Random random = new Random();
        return random.nextInt((max - min) + 1) + min;
    }
}

Output

Random Number:- 56
Random Number:- 57
Random Number:- 93
Random Number:- 60
Random Number:- 88


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0329 seconds.