Explain Codes LogoExplain Codes Logo

Generating a Random Number between 1 and 10 in Java

java
random-number-generation
java-utility-classes
performance-optimization
Nikita BarsukovbyNikita Barsukov·Nov 19, 2024
TLDR

Quickly snag a random number between 1 and 10 in Java with this snippet:

int jackpot = new Random().nextInt(10) + 1;

nextInt(10) cranks out an integer from 0 through 9 courtesy of the Random class. Tack on a +1 at the end, and you've got yourself a number from 1 to 10.

Getting to know the Random class

Better object management with Random

Economize on system resources by storing a Random instance in a field if you're dishing out lots of numbers:

Random karmaGenerator = new Random(); // Some believe karma is random too for (int i = 0; i < 10; i++) { int randomNumber = karmaGenerator.nextInt(10) + 1; // See, karma is fair! System.out.println(randomNumber); // Prints random number between 1 and 10 }

Refrain from creating a bunch of Random instances in no time. It's not only superfluous but might also lead to same numbers being duplicated.

Customize and adjust your number range

Say, you want to conjure numbers within a different range, play around with the argument in nextInt:

int luckyDrawMax = 50; // Try your own upper limit int luckyNumber = karmaGenerator.nextInt(luckyDrawMax - 1) + 1;

Voila, you've got a lucky number between 1 and your max limit.

Decoding the Random magma

Marrying Random with nextInt produces pseudo-random numbers using a secret linear congruential formula. Perfect for board games, maybe not so for securing a cryptocurrency wallet.

If you're going crypto, SecureRandom is a better match:

SecureRandom cryptonite = new SecureRandom(); // Because Superman needs a tough rival int cryptoStrongRandomNum = cryptonite.nextInt(10) + 1;

Looping for assurance

Satisfy your paranoia with a simple loop test:

for (int i = 0; i < 100; i++) { int randomNumber = karmaGenerator.nextInt(10) + 1; System.out.print(randomNumber + " "); // Rolling the dice a 100 times, huH? }

Highlights the randomness of your outputs faster than you can roll a dice!

Proper class import

To get everything running smoothly, don't forget your import statement:

import java.util.Random; // The ticket to Random concert!

That's your gateway to all the wonders Random and java.util package can bestow upon your code.