How to generate a random number between a given range in Java
Overview
In this shot, we'll see how to generate a random number in given range. Let's have a look at its syntax.
Syntax
startRange + (int) (Math.random() * ((endRange - startRange) + 1))
Syntax for getting a random number in a particular range in Java
Parameters
startRange: This is the starting point of the specified range.endRange: This is the end point of the specified range.Math.random(): This is used to generate a random value.(int): This typecasts the value we get from the product of the random number generated byMath.random()and the difference of the starting range and ending range plus one. So, if the value returned is a float or double value, it will convert it to an integer immediately.
Return value
The value returned is an integer value that is between startRange and endRange.
Example
class HelloWorld {public static void main( String args[] ) {// create some start rangesint startRange1 = 5;int startRange2 = 1;int startRange3 = 0;// create some end rangesint endRange1 = 50;int endRange2 = 10;int endRange3 = 3;// get the random between some rangesint rand1 = startRange1 + (int) (Math.random() * ((endRange1 - startRange1) + 1));int rand2 = startRange2 + (int) (Math.random() * ((endRange2 - startRange2) + 1));int rand3 = startRange3 + (int) (Math.random() * ((endRange3 - startRange3) + 1));// print the resultsSystem.out.println("A Random number between "+startRange1+" and "+endRange1+" is " +rand1);System.out.println("A Random number between "+startRange2+" and "+endRange2+" is " +rand2);System.out.println("A Random number between "+startRange3+" and "+endRange3+" is " +rand3);}}
Explanation
- Lines 4–6: We define some values that will serve as starting points for our ranges.
- Lines 9–11: We define some values that will be the end points of our ranges.
- Lines 14–16: We get some random numbers between the already defined ranges.
- Lines 19-21: We print the results to the console.