Java: Generate random numbers within a range


There are two classes that you can make use of to generate random numbers with a specified range,

  1. java.util.Random (added in Java 8)
  2. jmath.Random

Let us see an example to generate random numbers between 1 to 100.

Example 1: Random Numbers using Java 8 java.util.Random

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class JavaRamdonNumbersExample {

    public static void main(String[] args) {

        List<Integer> randomNumbers = new ArrayList<>();
        Random randomRange0to100 = new Random();
        for(int i = 0; i <=10; i++) {
            randomNumbers.add((int) randomRange0to100.nextInt(100));
        }
        System.out.println(randomNumbers);
    }
}
Output:

First Execution: [53, 44, 45, 28, 58, 53, 61, 91, 75, 6, 56]
Second Execution: [82, 57, 47, 97, 96, 66, 34, 26, 31, 37, 95]
Third Execution: [18, 84, 64, 74, 76, 4, 38, 24, 31, 11, 4]



Example 2: Random Numbers using jmath.Random

import java.util.ArrayList;
import java.util.List;

public class JavaRamdomNumbersExample {

    public static void main(String[] args) {
        List<Integer> randomNumbers = new ArrayList<>();
        for(int i = 0; i <=10; i++) {
            randomNumbers.add((int) (Math.random() * 100 + 1));
        }
        System.out.println(randomNumbers);
    }
}
Output:

First Execution: [55, 28, 60, 84, 70, 91, 39, 93, 20, 17, 61]
Second Execution: [37, 27, 60, 77, 64, 7, 33, 6, 12, 96, 30]
Third Execution: [3, 100, 65, 59, 13, 86, 26, 51, 13, 74, 59]

Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.