How to generate random numbers in a given range in java?

The java.util.Random class is used to generate random numbers. Java Random class objects are thread safe. It provides several methods to generate random numbers of type integer, double, long, float etc.

Note: Random class objects are not suitable for security sensitive applications so it is better to use java.security.SecureRandom in these cases.

We can use nextInt(limit) method to generate random numbers in a given range in java.

int nextInt(int n): It returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator’s sequence.

Example

package com.w3spoint;
 
import java.util.Random;
 
public class Test {
	public static void main(String args[]){
		Random random = new Random();		
		System.out.println("Random Integers between 0 to 100:");
		for(int i = 0; i < 10 ; i++){
			 System.out.println(random.nextInt(100));
		}
	}
}

Output

Random Integers between 0 to 100:
29
76
85
91
76
22
91
49
15
61
Content Protection by DMCA.com
Please Share