The Java Random class is a part of the java.util package and contains inbuilt methods to generate random numbers.
The following import statement must be included in your code when using this class.
import java.util.Random;
The most frequently used built-in methods for generating random numbers, are the following:
nextInt(): Returns a random int value within the range:
$ -2,147,483,648<=value<= 2,147,483, 647$
nextInt(int range): Returns a random int value within the range: $ 0 <= value < range $
nextDouble(): Returns a random double value within the range:
$ 0.0 <= value < 1.0 $
nextFloat(): Returns a random float value within the range:
$ 0.0 <= value < 1.0 $
nextLong(): Returns a random long value.
Note: To access the above methods, you need to create an instance of
Randomclass.
The following code generates some random numbers using the Java Random class:
import java.util.Random; //The import statementclass generateRandom {public static void main( String args[] ) {//Creating an object of Random classRandom random = new Random();//Calling the nextInt() methodSystem.out.println("A random int: " + random.nextInt());//Calling the overloaded nextInt() methodSystem.out.println("A random int from 0 to 49: "+ random.nextInt(50));//Calling the nextDouble() methodSystem.out.println("A random double: "+ random.nextDouble());//Calling the nextFloat() methodSystem.out.println("A random float: "+ random.nextFloat());//Calling the nextLong() methodSystem.out.println("A random long: "+ random.nextLong());}}
Free Resources