In  this tutorial, we will see “Several ways to generate a random number within range using Java?”

generate random number within range in java

Java – Multiple ways to Generate Random Number within a Range Share on X

Java 1st method:

/**
 * Generate Random Number within Range using Java 
 * @author Deepak Verma
 *
 */

import java.util.concurrent.ThreadLocalRandom;

public class Generate_Random_Number_within_Range_using_Java_Example_1 {
    
	public static void main(String args[]) {
    
		int minimum = 1;
        int maximum = 1000;
        
        System.out.println("Ten Random Numbers b/w 1 and 1000 are:");
        
        // Generate 10 random numbers between 1 and 1000
        for (int i = 0; i < 10; i++) {
            
        	int randomNumber = ThreadLocalRandom.current().nextInt(minimum, maximum + 1);
        	
        	System.out.println(randomNumber);
        
        }
        
    }
	
}

 

Output:

Ten Random Numbers b/w 1 and 1000 are:
1000
51
563
618
776
172
987
49
653
624

#### Remember above values may not be same for you as they will be random.

check if text or string present in a file using java 8

Java 2nd method:

/**
 * Generate Random Number within Range using Java 
 * @author Deepak Verma
 *
 */

import java.util.Random;

public class Generate_Random_Number_within_Range_using_Java_Example_2 {

	public static void main(String args[]) {
		
		int minimum = 1;
		int maximum = 1000;

		System.out.println("Ten Random Numbers b/w 1 and 1000 are:");

		//Create an object of Random class
		Random random = new Random();

		//Generate 10 random numbers between 1 and 1000
		for (int i = 0; i < 10; i++) {

			int randomNumber = random.nextInt((maximum - minimum) + 1) + minimum;

			System.out.println(randomNumber);

		}

	}

}

 

Output:

Ten Random Numbers b/w 1 and 1000 are:
987
373
299
446
425
885
458
830
541
899

#### Remember above values may not be same for you as they will be random.

generate random number within range in java

skip method java 8 stream

Java – Multiple ways to Generate Random Number within a Range Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts