The study will explain the procedure of generating random numbers between 1 and 10.
How to Generate Random Number between 1 and 10?
For generating random numbers between 1 and 10, you can follow these methods:
Let’s try to understand the working of these methods one by one.
Method 1: Generate Random Number Between 1 and 10 Using Math.random() Method
For obtaining a random number between 1 and 10, we will use the “Math.random()” method. Because it is a static method, the class name is used in its call. This method generates a random number of “double” type.
Syntax
Use the below-given syntax for the Math.random() method:
Here, the “max_num” is the maximum value that we will set as “10”, while the “min_num” is the minimum value that is “1” in case of generating a random number between 1 and 10.
Example
Firstly, we will create two integer type variables and specify “1” as “min_num” and “10” as “max_num”:
int max_num = 10;
As the random() method of the Math class returns the random value in double type, so we will create a double type variable named “rand_num” for storing randomly generated value:
Finally, print the randomly generated value on the console:
The output shows that a double type random number is generated between 1 and 10:
Now, let’s try to generate a random number of int type according to the specified range.
Method 2: Generate Random Number Between 1 and 10 Using Random.nextInt() Method
The Java “Random” class offers a “nextInt()” that can be utilized to generate an integer or int type random number. In our case, we will use the mentioned method to generate an integer type random number between 1 and 10.
Syntax
The below-given syntax can be used for generating a random number using the nextInt() method:
Here, the “nextInt()” method is called using an object of the Random class “rand” and passing “max_num” and “min_num” as arguments.
Example
In this example, firstly, we will create an instance of the Random class named “rand”:
Then, create an integer type variable “x” for storing a randomly generated integer number between 1 and 10 by invoking nextInt() method.
Lastly, print the generated random number on the console:
As you can see, we have successfully generated “6” as an int type variable between 1 and 10:
We have gathered different ways for generating a random number between 1 and 10.
Conclusion
For generating a random number between 1 and 10, you can use the random() method and the nextInt() method. The random() method produces double type random numbers, while the nextInt() method generates a random number in integer format. In this study, we explained the method related to obtaining a random number between 1 and 10.