Generating a Random Number between 1 and 10 in Java
Quickly snag a random number between 1 and 10 in Java with this snippet:
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:
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:
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:
Looping for assurance
Satisfy your paranoia with a simple loop test:
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:
That's your gateway to all the wonders Random and java.util package can bestow upon your code.
Was this article helpful?