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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | /** * 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | /** * 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: