Programming Examples

Java program to Generate a random number between given range


Write a Java Program which accept Lower bound (min) and Upper Bound (max) from user and generate a random number between min and max. 

Solution

import java.util.Scanner;
public class RandomNumberGenerator 
{
    public static void main(String[] args) {
        Scanner sc= new Scanner(System.in);
        System.out.print("Enter the lower bound (min): ");
        int min = sc.nextInt();        
        System.out.print("Enter the upper bound (max): ");
        int max = sc.nextInt();        
        int randomNumber=min + (int)(Math.random() * ((max - min) + 1));
        System.out.println("Random number between " + min + " and " + max + ": " + randomNumber);
    }

}
Output

Enter the lower bound (min): 1000

Enter the upper bound (max): 9999

Random number between 1000 and 9999: 1182


Online Exam Quiz for One day Exam Online Typing Test CCC Online Test 2026 Best Computer Training Institute in Prayagraj (Allahabad) Best Java Training Institute in Prayagraj (Allahabad) Best Python Training Institute in Prayagraj (Allahabad) O Level Online Test in Hindi Best Website and Software Company in Allahabad