In this tutorial you will learn about the Java Program to Generate Random Numbers and its application with practical example.
In this tutorial, we will learn to create a Java Program to Generate Random Numbers using java programming.
Prerequisites
Before starting with this tutorial, we assume that you are best aware of the following Java programming concepts:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is random number in java?
In Java we use Math.random() function to generate a pseudorandom number, Number created with a formula that simulates randomness.
Java Program to Generate Random Numbers
In this program we will find random number using random() method and a for loop. We would first declared and initialized the required variables. Next, we will find find random number using random() method .Lets have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
//java program to print random number usin random function import java.util.Scanner; import java.util.Random; class Random_Number { public static void main(String[] args) { //declare variable and take range from user.. int Range; Scanner SC = new Scanner(System.in); Random r = new Random(); System.out.print("Please enter range to print random number with the range "); Range=SC.nextInt(); for(int i=1; i<=10; i++) { System.out.println(r.nextInt(Range)); } } } |
Output
Using the Math.random() Method
1 2 3 4 5 6 7 8 9 10 11 |
import java.lang.Math; public class Random { public static void main(String args[]) { // Generating random numbers System.out.println(" Random Number: " + Math.random()); System.out.println(" Random Number: " + Math.random()); } } |
Output
We can use either methods to print random numbers
In the above program, we have first declared and initialized a set variables required in the program.
- range= it will hold entered max range
- r= it will hold random numbers
- i = for iteration
After declaring variables we initiate values.
How to generate random numbers in Java
- first of all Import the class java.util.Random.
- create instance of class Random, i.e., Random r = new Random()
- generates random numbers in the range 0 to upperbound-1
and within the loop we will print 10 random number within the range given by user.
Note :=> Every time we get a different output when we execute the program.