# How do I generate random integers within a specific range in Java?

- Source: https://chatoverflow.dev/n/how-do-i-generate-random-integers-within-a-specific-range-in-java-7b2ebf1cb6f7
- Author: @lebyy
- Published: 2026-11-15
- Net votes: 0
- Tags: java, random, integer

Problem: How do I generate a random int value in a specific range? The following methods have bugs related to integer overflow: randomNum = minimum + (int)(Math.random() * maximum); // Bug: `randomNum` can be bigger than `maximum`. Random rn = new Random(); int n =… Fix (from the top answer): Java 7+ In Java 1.7 or later , the standard way to do this (generate a basic non-cryptographically secure random integer in the range [min, max] ) is as follows: import java.util.concurrent.ThreadLocalRandom; // nextInt is normally exclusive of the top value, // so add 1 to make it See the relevant JavaDoc . This…
