The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);
Answer from nyanev on Stack Overflow
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › random › RandomGenerator.html
RandomGenerator (Java SE 17 & JDK 17)
January 20, 2026 - Every object that implements the RandomGenerator interface by using a pseudorandom algorithm is assumed to contain a finite amount of state. Using such an object to generate a pseudorandomly chosen value alters its state by computing a new state as a function of the current state, without reference ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › generating-random-numbers-in-java
Generating Random Numbers in Java - GeeksforGeeks
April 24, 2025 - This method can only generate random numbers of type Doubles. ... // Java program to demonstrate working of // Math.random() to generate random numbers import java.util.*; public class Geeks { public static void main(String args[]) { // Generating random doubles System.out.println("Random doubles: " + Math.random()); System.out.println("Random doubles: " + Math.random()); } }
Discussions

How do I use java.util.Random to generate random integers within a given interval?
Look at the javadocs for java.util.Random . What does passing an argument to the Random constructor do? It sets the seed for that instance. Well what does that mean? For pseudo-random generators like java.util.Random you must set an initial seed which it uses to generate values. Providing the same seed will generate the same values in the same order. In your code you've set the seed to 25, which explains why you always get the same value. Is there a way to construct an instance of java.util.Random without providing a seed? More on reddit.com
🌐 r/learnjava
8
1
October 21, 2020
Random number generator
Or just num = Random.nextInt(40) - 20? More on reddit.com
🌐 r/javahelp
7
3
September 11, 2019
How does one decide between ways to generate a random number in Java?
How random do you need it to be? If it's something unimportant like deciding which side of the screen an enemy will appear from, any way to do it will be good enough. If you're using the random number for an encryption key or something else critical for security, then it matters a lot, and you'll want to use a secure random number generator that can't be predicted, influenced, or compromised. More on reddit.com
🌐 r/learnprogramming
7
5
March 31, 2025
Question about random numbers in java
The easiest way to generate a random number in the range of 1 to 100 is by using java's built in Random function (you can also do it using Math, but it's less trivial). Random rand = new Random(); int i = rand.nextInt(100) + 1; The reason for the + 1 is because it's zero indexed by default (first value is 0) and without it you'd get a random number within the range 0 to 99. More on reddit.com
🌐 r/learnjava
5
3
September 14, 2016
🌐
W3Schools
w3schools.com › java › java_howto_random_number.asp
Java How To Generate Random Numbers
Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Server Java Syllabus Java Study Plan Java Interview Q&A Java Certificate ... You can use Math.random() method to generate a random number.
🌐
Baeldung
baeldung.com › home › java › java numbers › random number generators in java
Random Number Generators in Java | Baeldung
January 8, 2024 - In this tutorial, we’ll compare the new RandomGenerator API with the old Random API. We’ll look at listing all available generator factories and selecting a generator based on its name or property. We’ll also explore the new API’s thread-safety and performance. First, let’s take a look at Java’s old API for random number generation based on the Random class.
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Random.html
Random (Java Platform SE 8 )
1 week ago - Java™ Platform Standard Ed. 8 ... An instance of this class is used to generate a stream of pseudorandom numbers. The class uses a 48-bit seed, which is modified using a linear congruential formula. (See Donald Knuth, The Art of Computer Programming, Volume 2, Section 3.2.1.) If two instances ...
Find elsewhere
🌐
Sentry
sentry.io › sentry answers › java › generating random numbers in java
Generating random numbers in Java | Sentry
September 15, 2024 - To generate a random number in a range between a given start and end number: Use the end - start of your range as the input. Add start to the result. For example, the following code returns a random number between -5 and 5: import java.util.Random; ...
🌐
Medium
medium.com › @generativeai.saif › java-random-number-generator-5-methods-explained-with-examples-bf9e53abed3c
Java Random Number Generator: 5 Methods Explained with Examples | by Saif Ali | Medium
April 6, 2025 - ThreadLocalRandom is particularly useful in multithreaded applications where multiple threads need to generate random numbers independently. Using ThreadLocalRandom in a multithreaded environment: Here’s an example showing how to use ThreadLocalRandom in multiple threads: import java.util.concurrent.ThreadLocalRandom; public class MultithreadedRandomExample { public static void main(String[] args) { // Create multiple threads for (int i = 0; i < 5; i++) { Thread thread = new Thread(() -> { String threadName = Thread.currentThread().getName(); int randomValue = ThreadLocalRandom.current().nextInt(1000); System.out.println(threadName + ": Generated " + randomValue); }); thread.setName("Thread-" + i); thread.start(); } } }
🌐
Reddit
reddit.com › r/learnjava › how do i use java.util.random to generate random integers within a given interval?
r/learnjava on Reddit: How do I use java.util.Random to generate random integers within a given interval?
October 21, 2020 -

I am trying to generate a random number between 25 and 50, however every time I run my code, I keep getting 35. My teacher says it's because I planted a "seed" inside the Random declaration, but how would I change this into an interval?

import java.util.Random;

public class Range{

public static void main(String[] args) {

	`// TODO Auto-generated method stub`

Random rand = new Random(25);

int num = rand.nextInt(51);

System.out.println(num);

}

}

🌐
Coderanch
coderanch.com › t › 650127 › java › create-simple-random-number-generator
How do I create a simple random number generator for the number between 1 -10? (Beginning Java forum at Coderanch)
Just use the java.util.Random class from the standard library. ... Here is the simple code, I think I am mixing up Double, Int and Randoms. I am having issue it seems because I can't switch between an int and a double, but I am not sure how to use doubles in this case - or if I even need to. I want to generate a number from one to ten only.
🌐
Educative
educative.io › answers › how-to-generate-random-numbers-in-java
How to generate random numbers in Java
They rely on external physical ... String.format("0d", tenrand.nextInt(1000000000)); //Generates a random integer between 0 and 999999999 (inclusive), which is up to 10 digits long....
🌐
Reddit
reddit.com › r/javahelp › random number generator
r/javahelp on Reddit: Random number generator
September 11, 2019 -

I need to write a program that will generate a number between -20, and 20 for a school project. When attempting to turn it in I get a message stating that I dont have a randomized range from -20 to 20. Is it somethung with my code or just a website error?

My code: import java.lang.Math;

class Lesson_9_Activity_Two {

public static void main(String[] args) {

System.out.println((int)(Math.random()*40)-20);

} }

🌐
Crunchify
crunchify.com › java j2ee tutorials › how to generate random number in java with some variations?
How to Generate Random Number in Java with Some Variations? • Crunchify
December 28, 2025 - Updated on Dec 28, 2025by App · In Java, there is a method random() in the Math class, which returns a double value between 0.0 and 1.0. In the class Random there is a method nextInt(int n) , which returns a random value in the range of 0 ...
🌐
Tutorialspoint
tutorialspoint.com › home › java › java random number generation
Java Random Number Generation
September 1, 2008 - Java Vs. C++ ... The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0.
🌐
Computer Science Circles
cscircles.cemc.uwaterloo.ca › java_visualize
Java Visualizer
At the top of your program, write ... import java.util.*; won't work. How do I get shorter URLs? For example code, you can use #sampleFile=ExecLimit but in general, this is a feature that still needs to be implemented. You could use goo.gl for now. ... To share this visualization, click the 'Generate URL' button ...
🌐
iO Flood
ioflood.com › blog › java-random
Java Random: Generating Numbers with java.util.Random
March 5, 2024 - Math.random() is a simple, no-fuss way to get a random double, but requires additional steps to generate integers or other types of random values. Third-party libraries like Apache Commons Lang can provide additional utilities and flexibility, but require adding an external dependency to your project. While Java’s Random class and other methods offer powerful tools for generating random numbers, they’re not without their quirks.
🌐
HappyCoders.eu
happycoders.eu › java › random-number
Generating Random Numbers in Java
June 12, 2025 - Also present since Java 1.0 is the java.util.Random class. With it, you can generate a random int number as follows:
🌐
Nttdata-dach
nttdata-dach.github.io › posts › ms-newrandomgeneratorsinjava17
New Random Generators in Java 17
Java 17 introduced new random number generators. These provide longer cycles, improved statistical uniform distribution, improved threading support, and Streams API integration. This article provides a short introduction to random number generators and an overview of the improvements made in ...
🌐
nipafx
nipafx.dev › java-random-generator
Better Random Number Generation in Java 17 // nipafx
September 13, 2021 - Java 17 expands the API for random number generation to make it more usable, extensible, and robust with RandomGenerator and RandomGeneratorFactory at its core.
🌐
Reddit
reddit.com › r/learnprogramming › how does one decide between ways to generate a random number in java?
r/learnprogramming on Reddit: How does one decide between ways to generate a random number in Java?
March 31, 2025 -

I looked on the internet for ways to generate a random number in java, and I saw that there's at least three different ways to do it with native packages. Why are there so many? Are there downsides I should look out for or is it safe to just pick between them randomly? (ha)

Top answer
1 of 6
24
How random do you need it to be? If it's something unimportant like deciding which side of the screen an enemy will appear from, any way to do it will be good enough. If you're using the random number for an encryption key or something else critical for security, then it matters a lot, and you'll want to use a secure random number generator that can't be predicted, influenced, or compromised.
2 of 6
14
There are certainly downsides to each. The most truly "random" numbers are going to come from the stuff that looks like it's about cryptography or security, like SecureRandom. Those numbers are meant to be used to generate private keys and things. A random number generator whose results might be predictable by a skilled adversary is very scary there, so extra care is taken to be "very" random. In exchange, this will also be the slowest way to generate random numbers, so you usually don't want it unless you're doing something cryptography-related. Next is Random. It's a reasonable default. Its main weakness is that it is going to be worse if you have lots of threads all reading random numbers from it, which is probably not something you're doing. Finally, there's ThreadLocalRandom, which is great if you're in the above case. Its main disadvantage is that you cannot choose a seed number, which means you can't run the program again with exactly the same random numbers selected. This may not matter to you, and in that case, it works just as well or better than Random.