In this article, you will learn how to generate a random number ranging from 1 to 10 in JAVA by using the JAVA Math class which consists of methods that perform various tasks on numbers.
Java Math – Math.random()
Java provides three different techniques to generate a random number between 1 to 10 and they are given as,
- java.util.Random (Importing Packages)
- By using the Math.random method
- By using ThreadLocalRandom Class
The first method indicates the usage of the JAVA packages which contains many utility classes and one is the random-number generator, where nextInt, nextDouble, etc are involved.
Coming to the Third Method of technique, uses a java.util.concurrent.ThreadLocalRandom class which generates the integers, doubles, booleans, etc.
But in this article, I am explaining to you the second method of generating random numbers i.e, JAVA Math, where the Math class is used to find the maximum or minimum values between the given numbers. It also finds the square root and the absolute value of a number. Thus, Math.random() is used to generate a number randomly in a given range or others.
This method is far most useful and less burdened because it is simple. Study the approach given below to know more about the random method used here.
- To generate a random number between 1 to 10, the Math.random() is used and it returns a value between 0.0(inclusive) and 1.0(exclusive). Thus, it returns a double value which is not precise.
- By using int randomNum = (int)(Math.random() * 11) we can be more precise over the generating random number.
- We can import a built-in util package, as this package already contains many classes we may or may not use the Random class in the package. This can be simply represented by an asterisk (*).
- Hence this method returns the number of the specified data type like the integer, double, even boolean values.
- From the program, one can observe that the number 11 in the Math.random() * 11 indicates that the method generates numbers randomly in the range of 0 to 10.
- If the number is 10 and you want to generate a number between 1 to 10 randomly, then the output ranges only between 0 to 9 because 10 is exclusive.
import java.util.Random; // import java.util.*;
public class generateRandomNumber
public static void main(String args)
int randomNumber = (int)(Math.random() * 11); // Output Ranges from 0 to 10
System.out.println('The Random Number is ' +randomNumber);
The Random Number is 7