In Java 1.7 or later, I would use ThreadLocalRandom :
import java.util.concurrent.ThreadLocalRandom; // Get odd random number within range [min, max] // Start with an odd minimum and add random even number from the remaining range public static int randOddInt(int min, int max) { if (min % 2 == 0) ++min; return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1); } // Get even random number within range [min, max] // Start with an even minimum and add random even number from the remaining range public static int randEvenInt(int min, int max) { if (min % 2 != 0) ++min; return min + 2*ThreadLocalRandom.current().nextInt((max-min)/2+1); }
The reason for using ThreadLocalRandom is explained here . Also note that the reason we added +1 to the ThreadLocalRandom.nextInt () input is to make sure max is included in the range.
rouble
source share