Ad space (banner)
โ˜•Java Lessons
Lesson 53 / 68

Generating Random Numbers

This lesson covers generating random numbers in Java using the Random class, so you can build logic with a random element, like a dice roll or rock-paper-scissors. It's for anyone searching "Java Random usage."

The Random class generates random numbers. Use it to build something like a dice-rolling or lottery program. The result changes every time you run it.

The example generates a dice roll from 1 to 6 with rnd.nextInt(6) + 1. Since nextInt(6) returns a number from 0 to 5, notice the + 1 adjusting it into the 1-to-6 range.

A common early mistake is misjudging nextInt()'s range. Not knowing that nextInt(n) returns a value from 0 up to (but not including) n can leave you confused when you don't get the range you expected.

In real projects, you can also specify a fixed seed value when you want the same sequence of random numbers to be reproducible โ€” useful in a testing scenario.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Java directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)