Create Random Number in Java in a Range

Create Random Number in Java in a Range

In this tutorial, I will show you how to produce a random number in Java in a range.

There are two different ways by which Java random number can be created.

The primary route is to utilize nextInt() method of java.util.Random class and the second path are to utilize the random() method of java.lang.Math class.

Below I have shared one example for each.

Produce Random Number in Java in a Range

java.util.Random

The nextInt() method produces a random number in a range. Below example will create

random number in the middle of 1 and 10. Here 1 is comprehensive and 10 is select.

package com;
 
import java.util.Random;
 
public class RandomNumber{
	public static void main(String args[]){
		Random random=new Random();		
 
		//Generate random number between 1(inclusive) and 10(exclusive)
		for(int i=0;i<5;++i){
			System.out.println("Random Number in Java: "+random.nextInt(10));			
		}
	}
}

Output:

Create Random Number in Java in a Range

java.lang.Math

The random() method produces a random number in the middle of 0.0 and 1.0. Here 0.0 is comprehensive and 1.0 is elite.

In below example, I have duplicated the outcome with 10 and type throwing it into int to get a random number in the middle of 1 and 10.

package com;
 
public class RandomNumber{
	public static void main(String args[]){
		int random;
		
		//Generate random number in between 1(inclusive) and 10(exclusive) *** JustTechReview
		for(int i=0;i<5;++i){
			random=(int)(Math.random()*10);			
			System.out.println("Java Random Number: "+random);
		}
	}
}
Create Random Number in Java in a Range

If you found anything incorrect or have any doubts regarding above Java random number tutorial then comment below.

Leave a Comment

error: Alert: Content is protected!!