How to generate a Random Number between 1 and 10 in Java

Updated onbyAlan Morel
How to generate a Random Number between 1 and 10 in Java

Randomness is useful in programming for many things.

You can use randomness in programming to simulate dice rolls, lottery tickets, and other random events.

In this post, we will learn how to generate random numbers between 1 and 10 in Java.

Using Random Instance

The recommended way to use random is to create a new instance of the Random class, and then use the instance to generate random numbers.

This class is built-in to Java, so you don't need to use a third-party library to use it.

Simply import the package and use the nextInt method:

JAVA
import java.util.Random; public class Main { public static void main(String[] args) { Random random = new Random(); int min = 1; int max = 10; int value = random.nextInt(max + min) + min; System.out.println(value); } }
BASH
5

The parameter of the nextInt method is the maximum value that can be generated, and it includes 0. Because we don't actually want 0 to ever be generated if we want numbers between 1 and 10, we need to add 1 to the result, in our case, min.

Using Math class

Another way to generate random numbers is to use the Math class.

This class contains a random() method that returns a random float between 0 and 1.

This is useful because we just need to do a simple multiplication to get a random number between 1 and 10.

Here's an example:

JAVA
public class Main { public static void main(String[] args) { Random random = new Random(); int min = 1; int max = 10; int value = (int) (Math.random() * (max - min)) + min; System.out.println(value); } }
BASH
6

We have to cast it to an int because the Math.random() method returns a float, even though we want an int.

Conclusion

In this post, we learned how to generate random numbers between 1 and 10 in Java using the Random class and the Math class.

Either way works, it just depends on how you want to use it or what kind of data type you want in return.

Hopefully, you found this post interesting and useful. Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.